Hi,
I have ajax call from my view to controller for data update in PartialView.
Ajax call have disabled cache for this post action.
In controller is model changed properly (I see it in debug mode), but PartialView show me still after ajax return old data.
It is exactly the same scenario like here on StackOverflow:
http://stackoverflow.com/questions/1775170/asp-net-mvc-modelstate-clear
It is possible to solve this problem via using command: ModelState.Clear() in controller like in older MVC versions.
But i do not understand why work this so surprisingly...
Thank you
Miroslav
This is not a bug, but a side effect of a feature. ModelState
stores values it gets from request so in case of validation errors it can display the exact value that user entered - for instance imagine you have
public class EditModel
{
public int Count { get; set; }
}
<input type='text' asp-for='Count' />
User enters 'foo'
into the textbox and posts the form, but mvc can't map 'foo'
into an int
, so without ModelState
it would show back input with value of 0
instead of 'foo'
to user.
Generally you shouldn't change model by yourself in postbacks and if you absolutely have to, you must also to update ModelState
accordingly. Returning View
from postback should be reserved for validation errors, otherwise you should do a redirect which also solves problem with user refreshing window and doing postback again.
Thank You very much for your explanation.I will use clearing of modelstate in my scenario...
If is it so, please close this issue..
Yup, what @Kukkimonsuta is the reason.
I fail to understand why folks can't grok this. On a successful POST, redirect!! It's pretty standard practise and avoids the browser replay problems with forms (which is kinda 'web-101').
This SO question just goes to show how frustrating this 'issue' is to many developers, when if they'd just stop returning View()
from a POST action, the problem would go away.
Most helpful comment
This is not a bug, but a side effect of a feature.
ModelState
stores values it gets from request so in case of validation errors it can display the exact value that user entered - for instance imagine you haveUser enters
'foo'
into the textbox and posts the form, but mvc can't map'foo'
into anint
, so withoutModelState
it would show back input with value of0
instead of'foo'
to user.Generally you shouldn't change model by yourself in postbacks and if you absolutely have to, you must also to update
ModelState
accordingly. ReturningView
from postback should be reserved for validation errors, otherwise you should do a redirect which also solves problem with user refreshing window and doing postback again.