开发者

ValidationMessage not showing in custom asp.net mvc 2 editortemplate

开发者 https://www.devze.com 2022-12-18 02:48 出处:网络
I\'m having trouble adding a validationmessage to my custom editortemplate, this is the line I am using (I\'ve tried posting the entire template code but having no luck)

I'm having trouble adding a validationmessage to my custom editortemplate, this is the line I am using (I've tried posting the entire template code but having no luck)

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

If I put the validationmessage for t开发者_开发问答he model property outside of the template it works fine so I know the modelerror exists.

Any ideas?


I have an answer for you :)

You need to prefix the key of your property with the name of the property in the model.

For example, if your model looks like this:

public class MyModel
{
    public ChildModel Child { get; set; }
}

And you want to add an error message that the Child's template can see, you need to prefix the key of the error message as follows:

ModelState.AddModelError("Child.SomeKey", "Error message");

In your template view of ChildModel, display the error like this:

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


I use the strongly-typed html helpers.

Example

<div class="editor-label"><%= Html.LabelFor(model => model); %></div>
<div class="editor-field"><%= Html.TextBoxFor(model => model); %></div>
<div class="editor-error"><%= Html.ValidationMessageFor(model => model); %></div>

You could do the same thing without the strongly-typed helpers by using the Model ViewPage/Control property.

0

精彩评论

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

关注公众号