0

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

tereško
  • 58,060
  • 25
  • 98
  • 150
user2612665
  • 91
  • 1
  • 2
  • 11
  • can you please explain following sentence: "When I change the email value in the controller then set the active=true to make it readonly, the new email text value isnt updated." ? Can you also provide us action implementation? – Marcin Apr 24 '15 at 21:28
  • in the action sorry not controller, in the action I check to see if the user is active, if he is I ignore the email update and send back up in the model the old email and an active=true, which I expected would update the email box (basically ignore what the user put in) with the old email and make it readonly. But if the user is still not active I allow the email updating to happen and the email box is still editable. – user2612665 Apr 24 '15 at 21:53
  • Html helpers use model state value to bind to (not model values). You cant just change the model value and expect it to update (you would need to clear model state before returning the view) but this is the wrong approach anyway - you should be following the PRG pattern. For an explanation of this behavior, [refer this answer](http://stackoverflow.com/questions/26654862/textboxfor-displaying-initial-value-not-the-value-updated-from-code/26664111#26664111) –  Apr 25 '15 at 02:12
  • Thanks, I will look into this PRG pattern you speak off – user2612665 Apr 27 '15 at 18:05
  • Yup, I was doing it all wrong, your suggestion was correct, if you want to put it as an answer instead of a comment ill vote it as the answer. – user2612665 Apr 27 '15 at 20:02

1 Answers1

0

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

Community
  • 1
  • 1