I have an ASP.NET ViewModel like this:
public class ParentViewModel
{
public ChildViewModel Child { get; set; }
}
The ChildViewModel class in turn has properties that are decorated with the Required attribute and an appropriate error message. The reason for having a ViewModel set up like this is because the ChildViewModel is tied to a partial view and the partial view is rendered in different contexts. In one context, I am rendering the ChildViewModel’s partial view as such:
@Html.Partial("~/Views/Shared/_ChildView.cshtml", Model.AddressModel, new ViewDataDictionary
{
TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = "Child" },
})
The TemplateInfo causes the HTML inputs for the partial view to render with the correct name so they are correctly repopulated into the ParentViewModel on post back. ASP.Net is also correctly detecting when the child view model is missing information (ModelState.IsValid returns the correct result). However, the problem is it does not display the validation error messages. Any ideas on how to get the error messages to show?
This is all really the wrong way to go about this. Instead of Partial views, you should be using Templates.
If you create a Child.cshtml and put it in DisplayTemplates (or EditorTemplates if it’s an editor)Then, in your code you can simply do this: