尝试更新时模型对象不完整

时间:2012-06-18 21:44:33

标签: c# asp.net-mvc asp.net-mvc-3

我有以下行动方法:

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为null。所以我无法更新对象。我在这里做错了什么?

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

在视图中添加html标记HiddenFor,并确保在Get操作中填充UserId:

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

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

}