我正在尝试实现一个视图,在该视图中我将一个对象传递给它,该对象具有对其他对象的某些引用,编辑一些字段并将其恢复为持久化,问题是一旦我取回对象,这些引用就会返回为空,这是我的执行:
这是我传递给视图的模型:
public class TicketCreationModel
{
public SupportItem item { get; set; }
public Ticket ticket{ get; set; }
public Employee employee{ get; set; }
}
非常简单,模型有一张票、一个支持项目和一个员工。现在这是我将模型传递给视图的方法:
public ActionResult AssignSupportItem(int supportItemId)
{
Ticket ticket = GetTicket();
ticket.Item = repo.GetSupportItemFromId(supportItemId);
TicketCreationModel model = new TicketCreationModel();
model.employee = ticket.AccountableEmployee;
model.item = ticket.Item;
model.ticket = ticket;
return View(model);
}
第一行的 GetTicket() 方法返回会话对象,下面是实现:
private Ticket GetTicket()
{
Ticket ticket = (Ticket)Session["Ticket"];
if (ticket == null)
{
ticket = new Ticket();
Session["Ticket"] = ticket;
}
return ticket;
}
现在是采用模型并为工单启用一些编辑字段的视图:
@model WebUI.Controllers.TicketCreationModel
@{
ViewBag.Title = "AssignSupportItem";
}
<h2>AssignSupportItem</h2>
@using (Html.BeginForm()) { @Html.ValidationSummary(true)
<fieldset>
<legend>Creación ticket</legend>
<label>Descripción del problema</label>
<div class="editor-field">
@Html.EditorFor(model => model.ticket.Description)
@Html.ValidationMessageFor(model => model.ticket.Description)
</div>
@Html.HiddenFor(model => model.ticket.TicketId)
@Html.HiddenFor(model => model.item)
@Html.HiddenFor(model => model.employee)
<label>Solución aportada</label>
<div class="editor-field">
@Html.EditorFor(model => model.ticket.Solution)
@Html.ValidationMessageFor(model => model.ticket.Solution)
</div>
<label>Estado</label>
<div class="editor-field">
@Html.EditorFor(model => model.ticket.Status)
@Html.ValidationMessageFor(model => model.ticket.Status)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
最后是接收模型对象的视图上的表单调用的方法:
[HttpPost] public ActionResult AssignSupportItem(TicketCreationModel 模型) {
Ticket final = model.ticket;
final.Item = GetTicket().Item;
final.AccountableEmployee = GetTicket().AccountableEmployee;
repo.SaveTicket(final);
ViewBag.Message = "Su ticket ha sido agregado al sistema";
return View("AssignSupportItemResponse");
}
问题是我收到的模型对象的员工和项目属性为空,为什么会发生这种情况?我在我的模型上发送这些对象,为什么它们会丢失?我尝试使用会话对象恢复它们,但是一旦我尝试在我的上下文类中保留对象,我就会得到
“一个实体对象不能被多个 IEntityChangeTracker 实例引用”</p>
例外。
任何帮助将不胜感激,在此先感谢。