asp.net-mvchtml-helperreadonlyhtml.textboxfor

HTML.TextBoxFor is set readonly before value set


I have the following HTML helper textbox:

@Html.TextBoxFor(m => m.Email, Model.Active ? new { @readonly = "readonly", @style = "background:#E8E8E8" } : new Object { })

When I change the email value in the action (in the model being returned) then set the active=true (which is also in the model) to make it readonly, the email textbox value isnt updated with the new value coming from the model, and i checked to confirm that the model is going back with the new email and active=1.

Its as if the readonly is being set before the value from the model is being rendered.

Any help is appreciated, thankx


Solution

  • When you post back a model, its values are added to ModelState. Html helpers bind to the vales in ModelState, not the values of the model properties, so modifying the value of a model property in the POST method will not be reflected in the view unless you first clear model state before setting the value using

    ModelState.Clear(); // clears all properties
    

    or

    if (ModelState.ContainsKey("active"))
    {
        ModelState["active"].Errors.Clear(); //clears the property 'active'
    }
    

    The reason for this behavior is explained in the second part of this answer.

    However, clearing ModelState should be used with caution as it also clears validation errors, and in any case the correct approach is to follow the PRG pattern