我正在测试一个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");
}
CustomException:
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>
答案 0 :(得分:14)
你可以用这个衬里做到这一点:
@Html.Raw(HttpUtility.HtmlDecode(Html.ValidationMessageFor(m => m.Property).ToHtmlString()))
答案 1 :(得分:8)
您需要编写自定义帮助程序才能实现此目的。内置的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中显示错误消息,您还可以编写一个自定义帮助程序,不会像我在this post
中所示那样对错误消息进行HTML编码。
答案 2 :(得分:1)
尝试这个
在每条错误消息后附加
标记,并使用 Html.Raw()方法显示您的内容Html.Raw将解码HtmlContent。
you message like
Field 1 is required <br/>Field 4 is required<br/>
In View
Html.Raw("Yore Error Message")
答案 3 :(得分:1)
如果有人正在寻找它,以下是如何为验证摘要执行此操作:
@Html.Raw(HttpUtility.HtmlDecode(Html.ValidationSummary(true).ToHtmlString()))
答案 4 :(得分:0)
您是否在验证摘要中显示它们?我认为它不支持html用于换行等。我会根据显示html的验证摘要创建一个自定义html助手。
这同样适用于validationmessage,因此可能需要为该
制作一个自定义帮助器答案 5 :(得分:0)
我所做的就是把它们放在div中
<div class="Errors">
@Html.ValidationMessageFor(m => m.Name)<br/>
@Html.ValidationMessageFor(m => m.LName)<br />
</div>
然后创建一个类
.Errors {
color: red;
font-size: 10px;
font-weight: bold;
}
但如果你想做一个多线错误,那么Leinel提到的是最好的方法。我把它们束缚的原因是一些用户不会看到长形式的错误,他们只会开始给我们打电话.. ^^,< / p>