简体   繁体   中英

ASP.NET MVC - TryUpdateModel Not Working

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?

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");
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM