开发者

MVC2 ValidationMessage in template.master not rendering

开发者 https://www.devze.com 2023-01-07 21:13 出处:网络
I implemented the template.master technique described by Brad Wilson in this posting but I changed line 31 of his EditorTemplates/Template.master from:

I implemented the template.master technique described by Brad Wilson in this posting but I changed line 31 of his EditorTemplates/Template.master from:

<%= Html.ValidationMessage("", "*") %>

to:

<%= Html.ValidationMessage(ViewData.ModelMetadata.PropertyName)%>

so that the actual validation text will be displayed next to the controls. This renders nothing. If I move the same line into the object.ascx file, it renders, although not in the right spot in the layout. Is something with the metadata lifecycle not populating at this point in time?

UPDATE

I have this in my object.ascx and it wor开发者_运维技巧ks.

   <%= Html.Editor(prop.PropertyName)%>
   <p>
       <%=Html.ValidationMessage(prop.PropertyName)%>
   </p>

UPDATE2

This works in the template:

 <%= Html.ValidationMessage("")%>

I believe the scope of the template is at the control level, not the viewmodel level, so the "" has it just use the entire control model, rather than searching for a property from the viewmodel.


Something must be missing in your Model state or you've changed the key from being the property name.

The meaty code for ValidationMessage(anything) is pretty simple:

 private static MvcHtmlString ValidationMessageHelper(this HtmlHelper htmlHelper, ModelMetadata modelMetadata, string expression, string validationMessage, IDictionary<string, object> htmlAttributes) {
        string modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
        FormContext formContext = htmlHelper.ViewContext.GetFormContextForClientValidation();

        if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName) && formContext == null) {
            return null;
        }

        ModelState modelState = htmlHelper.ViewData.ModelState[modelName];
        ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors;
        ModelError modelError = ((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors[0];

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

The only other problem is if somehow you cleared out your validationMessage.


This works in the template:

 <%= Html.ValidationMessage("")%> 

I believe the scope of the template is at the control level, not the viewmodel level, so the "" has it just use the entire control model, rather than searching for a property from the viewmodel.

0

精彩评论

暂无评论...
验证码 换一张
取 消