Asp.net-Mvc

ValidationMessage 中的換行符

  • December 29, 2021

我正在測試 null 的事物列表。每次我找到一個時,我都會將它保存在一個數組中以在驗證消息中實現它。

我想要的輸出如下所示:

欄位 1 是必需的

欄位 4 是必需的

等等…

但我似乎無法開始新的生產線。

現在,它看起來像這樣:

欄位 1 為必填項 欄位 4 為必填項

有誰知道如何實現這一目標?

編輯:

控制器:

IDictionary<int, String> emptyFields = new Dictionary<int, String>();

foreach (Something thing in AnotherThing.Collection)
{
   if (thing.Property == null)
       emptyFields.add(thing.Index, thing.Name);                   
}

if (emptyFields.Any())
   throw new CustomException() { EmptyFields = emptyFields };

這個異常在這里處理:

catch (CustomException ex)
{                   
   ModelState.AddModelError("file", ex.GetExceptionString());
   return View("theView");
}    

自定義異常:

public class CustomException: Exception
{
   public IDictionary<int,String> EmptyFields { get; set; }
   public override String Label { get { return "someLabel"; } }
   public override String GetExceptionString()
   {
       String msg = "";
       foreach (KeyValuePair<int,String> elem in EmptyFields)
       {
           msg += "row: " + (elem.Key + 1).ToString() + " column: " + elem.Value + "<br/>";      
       }
       return msg;        
   }
}

看法:

<span style="color: #FF0000">@Html.Raw(Html.ValidationMessage("file").ToString())</span>

你可以用這一個班輪做到這一點:

@Html.Raw(HttpUtility.HtmlDecode(Html.ValidationMessageFor(m => m.Property).ToHtmlString()))

您將需要編寫一個自定義助手來實現這一點。內置ValidationMessageFor幫助器自動對值進行 HTML 編碼。這是一個例子:

public static class ValidationMessageExtensions
{
   public static IHtmlString MyValidationMessageFor<TModel, TProperty>(
       this HtmlHelper<TModel> htmlHelper, 
       Expression<Func<TModel, TProperty>> ex
   )
   {
       var htmlAttributes = new RouteValueDictionary();
       string validationMessage = null;
       var expression = ExpressionHelper.GetExpressionText(ex);
       var modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
       var formContext = htmlHelper.ViewContext.ClientValidationEnabled ? htmlHelper.ViewContext.FormContext : null;
       if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName) && formContext == null)
       {
           return null;
       }

       var modelState = htmlHelper.ViewData.ModelState[modelName];
       var modelErrors = (modelState == null) ? null : modelState.Errors;
       var modelError = (((modelErrors == null) || (modelErrors.Count == 0)) 
           ? null 
           : modelErrors.FirstOrDefault(m => !String.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0]);

       if (modelError == null && formContext == null)
       {
           return null;
       }

       var builder = new TagBuilder("span");
       builder.MergeAttributes(htmlAttributes);
       builder.AddCssClass((modelError != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName);

       if (!String.IsNullOrEmpty(validationMessage))
       {
           builder.InnerHtml = validationMessage;
       }
       else if (modelError != null)
       {
           builder.InnerHtml = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, modelState);
       }

       if (formContext != null)
       {
           bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage);
           builder.MergeAttribute("data-valmsg-for", modelName);
           builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant());
       }

       return new HtmlString(builder.ToString(TagRenderMode.Normal));
   }

   private static string GetUserErrorMessageOrDefault(HttpContextBase httpContext, ModelError error, ModelState modelState)
   {
       if (!String.IsNullOrEmpty(error.ErrorMessage))
       {
           return error.ErrorMessage;
       }
       if (modelState == null)
       {
           return null;
       }

       var attemptedValue = (modelState.Value != null) ? modelState.Value.AttemptedValue : null;
       return string.Format(CultureInfo.CurrentCulture, "Value '{0}' not valid for property", attemptedValue);
   }
}

然後:

public class MyViewModel
{
   [Required(ErrorMessage = "Error Line1<br/>Error Line2")]
   public string SomeProperty { get; set; }
}

在視圖中:

@model MyViewModel
@using (Html.BeginForm())
{
   @Html.EditorFor(x => x.SomeProperty)
   @Html.MyValidationMessageFor(x => x.SomeProperty)
   <button type="submit">OK</button>
}

如果您想在 ValidationSummary 中顯示錯誤消息,您還可以編寫一個自定義幫助程序,它不會對錯誤消息進行 HTML 編碼,如this post.

引用自:https://stackoverflow.com/questions/12909351