ASP.NET MVC - TryUpdateModel不起作用

时间:2013-05-22 19:28:25

标签: asp.net-mvc data-binding model model-binding model-binders

这是我的观点:

@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"/>
}

这是我的ActionMethod:

public RedirectToRouteResult Save()
{
    var user = new User();
    TryUpdateModel(user);
    Database.SaveEntity(user);
    return RedirectToAction("Index");
}

这是我的模特:@model Game.Model.User

当我调试并转发TryUpdateModel时,用户对象不会更新为我在视图中输入的值。

谁能看到我哪里出错了?

2 个答案:

答案 0 :(得分:2)

您没有收到后备后的表单数据。

试试这个:

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

要使用强类型视图,请执行以下操作:

@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"/>
}

然后更改您的操作方法签名以接收User

public RedirectToRouteResult Save(User user)
{
    TryUpdateModel(user);

    Database.SaveEntity(user);

    return RedirectToAction("Index");
}

答案 1 :(得分:1)

观看视频:

<input id="txtFirstName" type="text" />

我认为你应该添加name属性

<input id="txtFirstName" type="text" name="FirstName" />

或简单的方法:

@Html.TextBoxFor(m=>m.FirstName)