【问题标题】:Updating Model with entity collection使用实体集合更新模型
【发布时间】:2010-04-14 12:18:19
【问题描述】:

有一组名为 Book 和 Magazine 的实体继承自抽象类 PublishedItem。 PublishedItem 具有以下属性:ID、名称、出版商、作者列表、流派列表。 Book 实体具有 ISBN 属性,Magazine 实体具有 ISSN 属性。我只是想问一下,如果我对这些类型使用一组复选框,如何更新书籍或杂志的类型列表?

【问题讨论】:

    标签: asp.net-mvc entity-framework


    【解决方案1】:

    ASP.NET MVC 动作接受数组作为参数。

    [HttpPost]
    public ActionResult EditGenres(string[] genres, int ID)
    {
         PublishedItem item = GetPublishedItemByID(ID);
         item.Genres = genres.Select(x=> new Genre{ Name = x}); // this LINQ query just projects each string into a new genre. You can use w/e method you want to manipulate this string array into genres.
    
         return RedirectToAction("Success");
    }
    

    要填充数组,只需对表单字段的name 属性使用相同的值即可。

    <% Html.BeingForm() %>
       <input type="checkbox" value="Genre1" name="genres">
       <input type="checkbox" value="Genre2" name="genres">
       <input type="checkbox" value="Genre3" name="genres">
       <input type="checkbox" value="Genre4" name="genres">
    
       <input type="hidden" value="1" name="ID" />
       <input type="Submit" value="Submit Generes">
    <% Html.EndForm() %>
    

    【讨论】:

    • 我有一个空的流派构造函数。
    • @jean27 - “我有一个空的流派构造函数” - 我相信你可以从这篇文章中解决,添加一个部分类来定义构造函数,使用 new Genre() { Name = x },最坏的情况是使用流派数组中每个基因的 foreach 循环并将其添加到 item.Generes 集合中。
    • 我使用流派的 ID 作为复选框值,我只是用 ID 搜索流派并将其添加到书籍/杂志中。
    猜你喜欢
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多