MVC3 Razor ViewData
I have an online form. for example it asks for first name and last name. When they submit I send them to another view. this second view has a few more textboxes (password, email address, username) it also has first name and last name though. If they fill out the first form and fill in firstname/lastname i want the second form to display these values since they have alread开发者_JAVA百科y been filled in.
in the first form I am putting all the filled out information into TempData["entry"]
in the second form i am doing this check.
if (TempData["entry"] != null)
{
var _model = (AccountInformationModel)TempData["entry"];
ViewData["_firstName"] = _model.NameFirst;
ViewData["_lastName"] = _model.NameLast;
}
return View("Register");
i guess in my view im a bit confused on how to display this data in a textbox. I have this in my view but it doesnt seem to be working.
<div class="editor-label">
@Html.LabelFor(m => m.FirstName)
</div>
<div class="editor-field">
@Html.TextBox("FirstName", ViewData["FirstName"])
@Html.ValidationMessageFor(m => m.FirstName)
</div>
clearly the line that says...
@Html.TextBox("FirstName", ViewData["FirstName"])
doesnt work..
You're assigning the value to "_firstName"
ViewData["_firstName"] = _model.NameFirst;
And then trying to display "FirstName"
@Html.TextBox("FirstName", ViewData["FirstName"])
Try changing it to:
@Html.TextBox("FirstName", ViewData["_firstName"])
The other way to do this to avoid mistakes like this is to define a new class that will contain all your view data keys. This way your strings are contained in one location, making maintenance and changes easier.
public static class ViewDataKeys
{
public const string FirstName = "_firstName";
}
Then when you want to access it, you can use
ViewData[ViewDataKeys.FirstName] = _model.NameFirst;
精彩评论