Last post May 10, 2019 03:07 PM by pwnell
May 09, 2019 07:08 PM|pwnell|LINK
I have a form, and I post it. In the post code, I return a new model with one field modified. However depending on the use of the tag I see either the old or the new value.
<h1>@Html.DisplayFor(model => model.AccountQuoteInstance.Id)</h1>
After I post the form and the post method changed the AccountQuoteInstance.Id value from 9 to -1, and the page re-renders, I see the following output:
<input name="AccountQuoteInstance.Id" id="AccountQuoteInstance_Id" type="hidden" value="9" data-val-required="The Id field is required." data-val="true">
Why does that tag render -1 (the changed value, which is what I want) in the first two cases but in the case of asp-for it renders the old value which is 9?
May 09, 2019 07:18 PM|pwnell|LINK
What I did find is if I add the second line of code below to my controller on post in addition to the first line that I already had:
accountQuoteSet.AccountQuoteInstance.Id = -1;
I get the correct value. So I get that the model state is being used by the asp-for tag, however this seems to me like very undesirable behaviour to have the exact same tag in terms of syntax:
render different values based on the tag helper it is being used with. Why is this behaviour divergent?
May 10, 2019 06:41 AM|Sherry Chen|LINK
Hi pwnell ,
HTML Helpers uses the following order precedence when attempting lookup of the key:
For HTTP Post Actions, ModelState is always populated, and Html helpers get data from ModelState and not from model you pass when you call post action
, so modifying the Model (accountQuoteSet.AccountQuoteInstance.Id) has no effect.
You could also call ModelState.Clear() in the post action before you return your view, this way the info in the ModelState is going to be cleared and repopulated once your view is regenerated.
For more info about this issue (and other solutions), you could refer to the following links:
Best Regards ,
May 10, 2019 03:07 PM|pwnell|LINK
Thank you, that was very helpful. One thing that is still unclear to me is why, on the same page and at the same rendering time does
fetch the value from the Model property, and
from the ModelState dictionary? Should all helpers not fetch the data in the same order you have specified? Why the inconsistency? I can kind of understand that the first example above is not an MVC Helper - just plain Razor so it would bypass the POST
modelstate logic. But the @Html.DisplayFor - is that not an HTML helper too? Why does that use the model directly?