THe variable email below is used twice: first inside the <p> tag, and then is passed as a value of a textbox.
Question: Will both occurencies yield the same text? Believe it or not – they are different.
#UserProfileEditForm form = (UserProfileEditForm)ViewData["form"];
#string email = form.email;
<p>Email: ${HttpUtility.HtmlEncode(email)} <a class="ajax edit" href="${editEmailUrl}">Edit</a></p>
#if (form.editEmail)
#{
<form name="f_email" action="${editEmailUrl}" ....>
${Html.TextBox("form.email", email, new { @class="ajax string"}) }
</form>
#}
</div>
When I submit the above form to the server and intentionally type a malformed email address, the form will bounce back to me with an error message (omited here for clarity). The email value will appear twice in the HTML – all in line with the above code. The only problem is that the email value inside the <p> tag will be different from what’s in the text box. A sample output is below:
<p>Email: test@testing.test <a class="ajax edit" href="...">Edit</a></p>
<form class="ajax edititem" name="f_email" id="f_email" .....>
<input class="ajax string" id="form_email" type="text" value="changed````@testing.gov" />
</form>
</div>
How does this happen? How can the same variable, used twice in the code, assigned only once, deliver two different values???
Html.TextBox uses the previous value of the field, if available from the ModelState (this is preserved by MVC internals during request). Clear ModelState (completely or for this field) to force “email” variable value to be used.