首先,我对此很陌生,所以如果这是一个在其他地方回答的简单问题,请在此处链接我;我不想浪费任何人的时间(我在发布之前尝试了很长时间)。
因此,继续前进,我在 MVC3 项目中更新我的数据库中的信息(使用 EntityFramework)时遇到了一些问题。我有一个配置文件控制器(现在使用静态信息和可为空的 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方法可以正常工作,因为它在项目的这一部分开始之前已经过全面测试。我在哪里更新错误?