我在一个视图中更新模型数据和相关数据时遇到问题。所以,我有两个模型。
第一个模型描述了一个事件:
public class Event
{
public Event()
{
Guests = new List<Guest>();
}
public int ID { get; set; }
[Required]
public DateTime EventDate { get; set; }
[Required]
public string EventTime { get; set; }
[Required]
[StringLength(100)]
public string EventName { get; set; }
public int Room { get; set; }
[StringLength(50)]
public string UserName { get; set; }
public string UserPhone { get; set; }
public bool Status { get; set; }
public virtual List<Guest> Guests { get; set; }
[NotMapped]
public string DateToString
{
get { return EventDate.ToShortDateString(); }
set { EventDate = DateTime.Parse(value); }
}
第二个模特描述了客人:
public class Guest
{
public int ID { get; set; }
[Display(Name ="Vārds, uzvārds")]
public string GuestName { get; set; }
public string CardNumber { get; set; }
public bool Status { get; set; }
}
对于一个事件,可能有几个客人,关系是一对多。
现在,我创建了一个编辑视图,显示有关事件和附加到事件的访客的信息。代码是:
<div class="panel-body">
@{
@:<dl class="dl-horizontal">
if (Model.Guests != null)
{
for (int i = 0; i < Model.Guests.Count; i++)
{
@:<dt>@Html.DisplayNameFor(m => m.Guests[i].GuestName)</dt>
@:<dt>@Html.EditorFor(m => m.Guests[i].GuestName)</dt>
}
}
@:</dl>
}
</div>
在我的控制器中,在post方法中,我成功收到带有已编辑访客条目的模型。但是,当我将上下文状态设置为已修改时,我会收到错误:
附加“GuestAudit.Models.Guest”类型的实体失败,因为同一类型的另一个实体已具有相同的主键值。
我的控制器代码是:
public ActionResult Edit([Bind(Include = "ID,EventName,Room,EventDate,DateToString,EventTime,UserPhone,Status,Guests")] Event @event)
{
if (ModelState.IsValid)
{
@event.UserName = User.Identity.Name;
db.Entry(@event).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(@event);
}
这行代码给出了错误:
db.Entry(@event).State = EntityState.Modified;
可以在一个视图中编辑模型数据和相关数据吗?
答案 0 :(得分:0)
我终于找到了答案。因此,我修改了View代码,为每个相关记录添加了隐藏元素。现在视图代码如下:
<div class="panel-body">
@{
@:<dl class="dl-horizontal">
if (Model.Guests != null)
{
for (int i = 0; i < Model.Guests.Count; i++)
{
@:<dt>@Html.DisplayNameFor(m => m.Guests[i].GuestName)</dt>
@:<dt>@Html.EditorFor(m => m.Guests[i].GuestName)</dt>
@Html.HiddenFor(m => m.Guests[i].EventID)
@Html.HiddenFor(m => m.Guests[i].ID)
}
}
@:</dl>
}
</div>
控制器看起来像
public ActionResult Edit([Bind(Include = "ID,EventName,Room,EventDate,DateToString,EventTime,UserPhone,Status,Guests")] Event @event)
{
if (ModelState.IsValid)
{
@event.UserName = User.Identity.Name;
@event.Guests.ForEach(f => db.Entry(f).State = EntityState.Modified);
db.Entry(@event).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(@event);
}