5

我有以下操作方法:

public ActionResult ProfileSettings()
        {
            Context con = new Context();
            ProfileSettingsViewModel model = new ProfileSettingsViewModel();
            model.Cities = con.Cities.ToList();
            model.Countries = con.Countries.ToList();
            model.UserProfile = con.Users.Find(Membership.GetUser().ProviderUserKey);
            return View(model); // Here model is full with all needed data
        }

        [HttpPost]
        public ActionResult ProfileSettings(ProfileSettingsViewModel model)
        {
            // Passed model is not good
            Context con = new Context();

            con.Entry(model.UserProfile).State = EntityState.Modified;
            con.SaveChanges();

            return RedirectToAction("Index", "Home");
        }

@using (Html.BeginForm("ProfileSettings", "User", FormMethod.Post, new { id = "submitProfile" }))
        {
            <li>
                <label>
                    First Name</label>
                @Html.TextBoxFor(a => a.UserProfile.FirstName)
            </li>
            <li>
                <label>
                    Last Name</label>
                @Html.TextBoxFor(a => a.UserProfile.LastName)
            </li>
...
<input type="submit" value="Save" />
...

当我在 POST 方法中点击提交时收到的模型不完整。它包含 FirstName、LastName 等。但 UserID 为空。所以我不能更新对象。我在这里做错了什么?

4

3 回答 3

2

MVC 仅根据请求中的内容重建您的模型。在您的特定情况下,您只提交 FirstName 和 LastName,因为这些是@Html.TextBoxFor()您的视图中包含的唯一调用。MVC 模型的行为不像ViewState,它没有存储在任何地方。

您也不想在视图模型中包含整个实体。如果您只需要 ID,那么这应该就是您所包含的所有内容。然后,您将再次从 DAL 加载您的实体,更新需要更改的属性,然后保存您的更改。

于 2012-06-18T21:53:40.390 回答
1

您应该将 UserId 存储为表单中的隐藏字段。

于 2012-06-18T21:52:24.140 回答
1

在您的视图中添加一个 html 标签 HiddenFor,并确保您在 Get 操作中填充了 UserId:

@using (Html.BeginForm("ProfileSettings", "User", FormMethod.Post, new { id = "submitProfile" }))
        {

@Html.HiddenFor(a => a.UserProfile.UserId)
// your code here..

}
于 2012-06-18T22:23:35.253 回答