Custom ValidationSummary template Asp.net MVC 3

前端 未结 7 2326
耶瑟儿~
耶瑟儿~ 2020-11-30 18:59

I am working on a project with Asp.Net MVC3

In a View I have @Html.ValidationSummary(true) and as usually it produces

7条回答
  •  臣服心动
    2020-11-30 19:56

    This question details the procedure of writing custom validation summary.

    EDIT This will do what you want:

    public static class LinqExt 
    {
        public static string MyValidationSummary(this HtmlHelper helper, string validationMessage="")
        {
            string retVal = "";
            if (helper.ViewData.ModelState.IsValid)
                return "";
    
            retVal += "
    "; if (!String.IsNullOrEmpty(validationMessage)) retVal += helper.Encode(validationMessage); retVal += ""; retVal += "
    "; foreach (var key in helper.ViewData.ModelState.Keys) { foreach(var err in helper.ViewData.ModelState[key].Errors) retVal += "

    " + helper.Encode(err.ErrorMessage) + "

    "; } retVal += "
    "; return retVal.ToString(); } }

    The code is self explanatory; just enumerating through modelstate errors and wrapping errors in dom element of your choice. There is an error that is if i use it like:

    <%:Html.MyValidationSummary()%>
    

    It will display html tags on the page as text rather than rendering it.

    <%=Html.MyValidationSummary()%>
    

    This works fine.

提交回复
热议问题