保存时,ASP.net mvc EntityCollection为null

时间:2011-01-13 15:28:06

标签: asp.net-mvc entity-framework

我一直试图解决这个问题超过一天,但我无法让这个工作。 我有一个asp.net MVC网站,它使用entityframework作为其数据模型。 我需要能够编辑包含Release

的复杂List<ReleaseDescription>实体

我有以下型号(显然我无法上传图片所以我只需输入它):

public class Release
{
    public string Version
    ..some other primitive properties
    public EntityCollection<ReleaseDescription>
}

public class ReleaseDescription
{
    public string Description
    public Language Language
}

public class Language
{
    public string ISOCode
    public string Description
}

在网上寻找此问题的解决方案时。我发现使用EntityCollection(参见列表Release.ReleaseDescription)并不是一个好主意所以在部分类Release中我创建了一个额外的属性ReleaseDescriptionList,它将这个entityCollection转换为{{1}通过getter,它没有setter。

问题在于,在保存时,我的List<ReleaseDescription>甚至release.ReleaseDescription在项目应该在其中时始终为空。

以下是我的其余代码:

我的Edit.aspx代码看起来像这样

release.ReleaseDescriptionList

DescriptionRelease中的asp代码如下所示:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Server.DM.Release>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>Edit</h2>
    <% using (Html.BeginForm()) {%>
        <%: Html.ValidationSummary(true) %>

        ... (Code for the primitive properties (works all fine)

        <fieldset>
            <legend>Descriptions</legend>

                <% for(var i =0; i<Model.ListReleaseDescriptions.Count; i++)
                {%>
                   <%: Html.EditorFor(x => Model.ListReleaseDescriptions[i], "ReleaseDescriptionRow")%>
                <%} %>

                <%= Html.ActionLink("Add another...", "AddDescription", Model) %>

        </fieldset>

        <p>
            <input type="submit" value="Save" />
        </p>

    <% } %>

    <div>
        <%: Html.ActionLink("Back to List", "Index") %>
    </div>

</asp:Content>

(我无法在多行上面获得代码块对不起)

当我点击编辑屏幕中的保存按钮并进入我的ActionController

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Server.DM.ReleaseDescription>" %>Language: <%= Html.TextBoxFor(x => x.Language.ISOCode) %>Qty: <%=Html.TextBoxFor(x => x.Description)%>

[HttpPost] public ActionResult Edit(Release release) 在其中包含3个项目时不包含任何数据。 在解决此问题时,我们非常感谢您的帮助!

(ps:是的,我知道在这个论坛和其他论坛上有类似的主题,但似乎没有一个对我有用。)

1 个答案:

答案 0 :(得分:0)

好的,经过大量的搜索,我终于找到了解决问题的答案。

我已经做了一个额外的属性来弥补EntityCollection,但它看起来像这样:

public IList<ReleaseDescription> ListReleaseDescription
{
    get
    {
        return ReleaseDescription.ToList();
    }
}

这没有用,所以我用它做了一个简单的属性:

public IList<ReleaseDescription> ListReleaseDescription{get; set;}

我在我的控制器中填充了这个属性。这最终修复了我的问题,我在保存时收到了所有数据!当解决方案如此简单时,我无法相信我浪费了1.5天。