Recently I faced a strange
problem with MVC @HTMLHelper class and after post, the view is not
getting updated with new data.
MODELSTATE.CLEAR ();
ModelState.Remove(“ID”);
I have one hidden field (property
name = ‘ID’ as below) on HTML Form to track the new entity or existing entity,
so on basis of ID value, I need to make a call to create new entity or update
the existing entity.
@using (Html.BeginForm("", "",
FormMethod.Post, new { @class = "form-inline" }))
{
@Html.HiddenFor(m => m.ID)
}
But when I tried to update the
recently created entity and I found that the value of ID property is 0 in
model, it should hold newly created entity ID and it seems like the view model
is not getting refreshed after post
I found the two possible solution
to solve this view model restressed issue.
1. Clear
ModelState Value in controller:
You can clear the model state before returning model to view and ModelState.Clear()
method is usually used to clear errors but it is also used to force the MVC
engine to rebuild the model to be passed to your View.
MODELSTATE.CLEAR ();
2. Second option
Instead of clear of all ModelState dictionary Values and validation error
message, you can only remove desired ID property /Field and MVC Engine will
rebuild value only for removed property
ModelState.Remove(“ID”);
Other ASP.NET
MVC related topics:
Thanks for visiting!!
1 comment:
Thank you ! You've just saved my day.
Is this an error in MVC ? I think so. Setting the model explicitly should be preferred before Viewstate in my opinion
Post a Comment