我正在尝试修改活动编辑页面,以便我可以参与更多信息。 为了简化,我有以下内容。
模型
public class Activity
{
public int ActNo { get; set; }
public string ActName { get; set; }
public virtual ICollection<Attendance> Attendances { get; set; }
}
public class Attendance
{
public int ActNo { get; set; }
public string StudentID { get; set; }
public virtual Activity Activities { get; set; }
public virtual Student Students { get; set; }
}
public class Student
{
public string StudentID { get; set; }
public string EnglishName { get; set; }
public virtual ICollection<Attendance> Attendances { get; set; }
}
在编辑页面中,我想显示学生信息(包括那些在考勤中没有相关记录的人)。所以我有一个ViewModel。
public class ActivityEditView
{
public Activity SelectedActivity { get; set; }
public Student Students { get; set; }
}
查看
@model <projectname>.ViewModels.ActivityEditView
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.SelectedActivity.ActNo)
<div class="form-group">
@Html.LabelFor(model => model.SelectedActivity.ActName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.SelectedActivity.ActName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.SelectedActivity.ActName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
我将model.ActNo和model.ActName更改为model.SelectedActivity.ActNo和model.SelectedActivity.ActName
控制器
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ActNo,ActName")] Activity activity)
{
if (ModelState.IsValid)
{
db.Entry(activity).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(activity);
}
现在一切都正确显示但我无法更新信息。 db.SaveChanges()发生错误。
存储更新,插入或删除语句会影响意外的行数(0)。自实体加载以来,实体可能已被修改或删除。
我不知道如何更新控制器部分中的代码。有什么想法吗?
答案 0 :(得分:0)
您可能绑定到null
。尝试:
[Bind(Prefix = "SelectedActivity")]Activity activity
答案 1 :(得分:0)
您需要修改您的类(活动)以指定可绑定属性,如下所示:
[Bind(Include = "ActNo,ActName")]
public class Activity
{
public int ActNo { get; set; }
public string ActName { get; set; }
public virtual ICollection<Attendance> Attendances { get; set; }
}
然后在您的POST操作中,您需要传递视图模型的实体( ActivityEditView ):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ActivityEditView activityEdit)
{
if (ModelState.IsValid)
{
db.Entry(activityEdit.SelectedActivity).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(activity);
}