1

这是我的观点:

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

这是我的动作方法:

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

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

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

谁能看到我哪里出错了?

4

2 回答 2

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");
}
于 2013-05-22T19:30:18.747 回答
1

在视图中:

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

我认为你应该添加name属性

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

或者一个简单的方法:

@Html.TextBoxFor(m=>m.FirstName)
于 2013-05-23T07:23:04.730 回答