首先,我对此非常陌生,所以如果这是一个简单的问题在其他地方回答,请将我链接到那里;我不想浪费任何人的时间(我在发布前试了很长时间)。
所以,继续,我在更新MVC3项目中的数据库(使用EntityFramework)中的信息时遇到了一些麻烦。我有一个配置文件控制器(使用静态信息,现在可以使用nullable int进行测试),如下所示:
public ViewResult Edit(int? memberID)
{
Member member = repository.Members.GetMember(12985);
return View(new ProfileEditViewModel
{
MemberID = member.id,
FirstName = member.fname,
LastName = member.lname,
HomePhone = member.home_phone,
CellPhone = member.cell_phone,
Address = member.street,
City = member.city,
State = member.state,
Zip = member.zip,
Email = member.email,
Sex = member.sex,
MemberType = member.membertype,
TypeOfCar = member.typeofcar
});
}
然后我得到一个强类型视图,就像这样开始:
@using (Html.BeginForm()) {
<div class="editor-label">
<label for="fname">First Name:</label>
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
并为我的ViewModel的每个属性将表单字符串向下,除了MemberID。它以
结束<p>
<input type="submit" value="Save" />
@Html.ActionLink("Cancel", "Summary")
</p>
回到我的控制器中,我有了补充方法:
[HttpPost]
public ActionResult Edit(ProfileEditViewModel memberViewModel)
{
Member member = repository.Members.GetMember(memberViewModel.MemberID);
if (ModelState.IsValid)
{
member.fname = memberViewModel.FirstName;
member.lname = memberViewModel.LastName;
member.home_phone = memberViewModel.HomePhone;
member.cell_phone = memberViewModel.CellPhone;
member.street = memberViewModel.Address;
member.city = memberViewModel.City;
member.state = memberViewModel.State;
member.zip = memberViewModel.Zip;
member.email = memberViewModel.Email;
member.sex = memberViewModel.Sex;
member.membertype = memberViewModel.MemberType;
member.typeofcar = memberViewModel.TypeOfCar;
repository.Members.UpdateMember(member);
return RedirectToAction("Summary");
}
else
{
//there is something wrong with the data
return View(member);
}
问题是,当我尝试更新成员的信息时,我得到一个“序列包含无元素”错误,即使我知道我指定的MemberID有效,因为我能够进入更新页面,而我知道UpdateMember方法正常工作,因为它在项目的这一部分开始之前已经完全测试。我在哪里更新了错误?
答案 0 :(得分:1)
你错过了
@Html.HiddenFor(m => m.MemberID)
在你看来。