views:

60

answers:

2

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: [email protected] <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???

A: 

You could have a second thread running, where the second thread modifies the value of email. Or some operation that occurs between the first and second output could be overwriting the value (or pointer, if ASP.NET allows direct pointer manipulation - I'm not very familiar with ASP.NET). Or the Html.TextBox method could be altering the value (is this a custom implementation, or an extension of a standard library?).

atk
Spark is a view engine. See http://sparkviewengine.codeplex.com/ or http://sparkviewengine.com/
Jason Rowe
the variable is local, so no way for another thread to alter it (and especially no way to do it consistenly on every page submission).
Andy
Then I'd lean toward Html.TextBox doing something. What happens if you copy/paste the HtmlEncode(email) after the Html.TextBox call? Does the second call to HtmlEncode still have the altered output?
atk
+1  A: 

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.

queen3
Andy
By the way, do not do ModelState.Clear() if you want to keep validation errors; do smth like ModelState["email"].Value = new ValueProviderResult(...).
queen3