The top level IsValid property should reflect all errors! However, if you don't pass to the partial view the dictionary with all errors errors are not displayed properly in the partial view.
For this purpose you have to use this overload of the RenderPartial:
All-Star
15941 Points
3575 Posts
Re: Validation of model in side model
Oct 12, 2010 03:55 AM|francesco abbruzzese|LINK
The top level IsValid property should reflect all errors! However, if you don't pass to the partial view the dictionary with all errors errors are not displayed properly in the partial view.
For this purpose you have to use this overload of the RenderPartial:
RenderPartial(HtmlHelper, String, ViewDataDictionary)
Where the data dictionary is built as follows:
<div style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"> ViewDataDictionary<TItem> dataDictionary = new ViewDataDictionary<TItem>(Item.Value);</div> <div style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"> dataDictionary.TemplateInfo.HtmlFieldPrefix = BasicHtmlHelper.AddField(prefix, "$.Item.Value");</div> <div style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"> BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix);</div>ViewDataDictionary<YourSubModelType> dataDictionary = new ViewDataDictionary<YourSubModelType>(YourSubModel);
dataDictionary.TemplateInfo.HtmlFieldPrefix = PrefixFromPrincipalModel;
CopyRelevantErrors(dataDictionary.ModelState, Html.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix);
The Copy Relevant errors copy in the error dictionary of the partial vie only the relevant errors, i.e. only the ones with the right prefix;
its implemntation is something like:
void CopyRelevantErrors(ModelStateDictionary destination, ModelStateDictionary origin, string prefix)
{
foreach (KeyValuePair<string, ModelState> pair in origin)
{
if (pair.Key.StartsWith(prefix)) destination.Add(pair);
}
}
Mvc Controls Toolkit | Core Mvc Controls Toolkit