Reputation: 5480
This is my View:
@using (Html.BeginForm("Save", "Test", FormMethod.Post))
{
<label for="txtFirstName">First Name</label>
<input id="txtFirstName" type="text" />
<label for="txtLastName">Last Name</label>
<input id="txtLastName" type="text" />
<label for="txtUsername">Username</label>
<input id="txtUsername" type="text" />
<label for="txtEmail">Email</label>
<input id="txtEmail" type="text" />
<input type="submit" value="Save"/>
}
This is my ActionMethod:
public RedirectToRouteResult Save()
{
var user = new User();
TryUpdateModel(user);
Database.SaveEntity(user);
return RedirectToAction("Index");
}
This is my Model: @model Game.Model.User
When I debug and step-over TryUpdateModel, the user object doesn't update to the values I entered in the View.
Can anyone see where I am going wrong?
Upvotes: 1
Views: 3994
Reputation: 677
On View:
<input id="txtFirstName" type="text" />
I think you should add name
property
<input id="txtFirstName" type="text" name="FirstName" />
or a simple way:
@Html.TextBoxFor(m=>m.FirstName)
Upvotes: 1
Reputation: 102408
You're not receiving the form data that was post-backed.
Try this:
public RedirectToRouteResult Save(string txtFirstName, string txtLastName,
string txtUsername, string txtEmail)
{
var User = new User();
user.FirstName = txtFirstName;
user.LastName = txtLastName;
user.Username = txtUsername;
user.Email = txtEmail;
TryUpdateModel(user);
Database.SaveEntity(user);
return RedirectToAction("Index");
}
To use a strongly typed view, do this:
@model Game.Model.User
@using (Html.BeginForm("Save", "Test", FormMethod.Post))
{
@Html.LabelFor(m => m.FirstName)
@Html.EditorFor(m => m.FirstName)
@Html.LabelFor(m => m.LastName)
@Html.EditorFor(m => m.LastName)
@Html.LabelFor(m => m.Username)
@Html.EditorFor(m => m.Username)
@Html.LabelFor(m => m.Email)
@Html.EditorFor(m => m.Email)
<input type="submit" value="Save"/>
}
and then change your action method signature to receive a User
:
public RedirectToRouteResult Save(User user)
{
TryUpdateModel(user);
Database.SaveEntity(user);
return RedirectToAction("Index");
}
Upvotes: 2