您可以按照與Html.ValidationMessageFor相同的行創建HTML助手擴展方法。
下面是我快速打開的一個示例,但您可以進一步擴展它。看看http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/ValidationExtensions.cs以獲得更多創意。
這會輸出一個span
標籤,其中css類別爲field-validation-valid
。
<span class="field-validation-valid">My success message</span>
查看
@Html.ValidationSuccessMessageFor(m => m.MyProperty, "My success message")
擴展方法
public static MvcHtmlString ValidationSuccessMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return ValidationSuccessMessageFor(htmlHelper, expression, null, new RouteValueDictionary());
}
public static MvcHtmlString ValidationSuccessMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string validationMessage)
{
return ValidationSuccessMessageFor(htmlHelper, expression, validationMessage, new RouteValueDictionary());
}
public static MvcHtmlString ValidationSuccessMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string validationMessage, object htmlAttributes)
{
return ValidationSuccessMessageFor(htmlHelper, expression, validationMessage, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString ValidationSuccessMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string validationMessage, IDictionary<string, object> htmlAttributes)
{
return ValidationMessageHelper(htmlHelper, ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData), ExpressionHelper.GetExpressionText(expression), validationMessage, htmlAttributes);
}
private static MvcHtmlString ValidationMessageHelper(this HtmlHelper htmlHelper, ModelMetadata modelMetadata, string expression, string validationMessage, IDictionary<string, object> htmlAttributes)
{
var modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
FormContext formContext = htmlHelper.ViewContext.ClientValidationEnabled ? htmlHelper.ViewContext.FormContext : null;
if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName) && formContext == null)
{
return null;
}
var modelState = htmlHelper.ViewData.ModelState[modelName];
if (modelState == null || (modelState != null && (modelState.Errors == null || modelState.Errors.Count > 0)))
{
return null;
}
var builder = new TagBuilder("span");
builder.MergeAttributes(htmlAttributes);
builder.AddCssClass(HtmlHelper.ValidationMessageValidCssClassName);
if (!String.IsNullOrEmpty(validationMessage))
{
builder.SetInnerText(validationMessage);
}
return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}
它是由設計,你只會增加錯誤消息到模型狀態。如果你想要成功的消息,只需使用另一種視圖模型或視圖包來實現。 – Spock
'ModelState.IsValid' – David
@David'ModelState.IsValid'表示布爾值,我想知道如何添加像ModelState.AddModelSuccess成功消息,不幸的是這種方法不可用? – sridharnetha