How does asp.net MVC remember my incorrect values on postback?

后端 未结 3 1238
忘了有多久
忘了有多久 2021-01-05 15:27

This is working, but how???

I have a controller action for a post:

[AcceptVerbs(HttpVerbs.Post )]
public ActionResult Edit(Person person)
{
   bool i         


        
相关标签:
3条回答
  • 2021-01-05 15:58

    The previously entered value is stored in the ModelState. When you have an error on the form, the helper pulls the value from the ModelState instead of using either values from the Model or the ones specifically supplied (under the hood, if you don't supply an explicit value it will default to the model value if there is one when there are no errors).

    0 讨论(0)
  • 2021-01-05 16:15

    I had some code in the 'postback' that would remove invalid promo-codes and capitalize the response. Even if you update the model with the new value it won't be displayed because the ModelState value takes precedence (as others have already answered).

      <%= Html.TextBox("PromoCode", Model.PromoCodes) %>
    

    But if you have a case where this was happening and you don't want the old value persisted you need to do this:

    ModelState.Remove("PromoCode"); 
    

    or explicitly set the new value into modelstate (probably the better approach) :

    ModelState.SetModelValue("PromoCode", 
          new ValueProviderResult(newValue, newValue, CultureInfo.CurrentCulture));
    
    0 讨论(0)
  • 2021-01-05 16:18

    ModelState holds KeyValuePairs for every form element with the key being the field name and the value is what you put in the field. Then the Html Helpers look in ModelState and if you don't explicitly specify a value, they will pull the value from ModelState.

    0 讨论(0)
提交回复
热议问题