Reputation: 943
Please help me to implement the editor template when Model and ModelState mismatch.
For example: Model.A == 'x', ViewData.ModelState['A'] == 'y'.
That can occur when form was posted invalid.
Native templates take this in account and display right value from the ModelState. But i could't find their sources.
I need to implement this in my own temlate. Should i just check for a present value in ModelState and use it if it is set. Or may you suggest a better way?
Upvotes: 1
Views: 166
Reputation: 2844
I had a look at the HtmlHelpers (editors) and came up with this. In the example the model/ value is an integer:
var value = Model; //value according to the model
var fieldName = ViewData.TemplateInfo.GetFullHtmlFieldName("");
ModelState modelState;
if(ViewData.ModelState.TryGetValue(fieldName, out modelState) && modelState.Value != null)
{
value = (int?) modelState.Value.ConvertTo(typeof(int?), null);
}
Now the value contains the model value or the posted ModelState value (the attemptedValue).
Upvotes: 1