模型的对象引用在视图中丢失

时间:2013-04-02 21:09:07

标签: asp.net asp.net-mvc asp.net-mvc-3 entity-framework asp.net-mvc-4

我正在试图实现一个视图,在这个视图中我传递了一个对象,其中包含对其他对象的某些引用,编辑一些字段并将其恢复为persis,问题是这些引用在返回对象后返回null ,继承人我的实施:

这是我传递给视图的模型:

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(真)

<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 model)         {

        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");

    }

问题是我收到的模型对象的employee和item属性为null,为什么会这样?我在模型上发送这些对象为什么会迷路?我尝试使用会话对象恢复它们,但是一旦我尝试将对象保存在我的上下文类中,我就得到了

“IEntityChangeTracker的多个实例无法引用实体对象”

异常。

任何帮助将不胜感激,提前谢谢。

1 个答案:

答案 0 :(得分:2)

您的模型实际上相当复杂。 Controller无法从提交的数据中重新组装您的模型。尝试创建一个仅包含实际需要显示的“简单”属性(即字符串,整数等)的视图模型。提交后,您必须从商店获取员工和项目,然后更新其值。