CheckBoxList用于ASP.NET MVC中的多对多关系

时间:2015-04-28 02:15:19

标签: c# asp.net-mvc razor html-helper checkboxlist

我正在尝试在MVC中实现一个多对多关系(文章 - 类别)的复选框列表。我试过这个,但我不行。有没有人知道一个不同的和正确的方法来获得它。

在域模型中:

public class Article
{

    public int Id { get; set; }


    [Required]
    [StringLength(255)]
    public string Title { get; set; }

    [Required]
    public string Body { get; set; }

    [Required]
    public DateTime DateCreated { get; set; }

    [Required]
    [StringLength(255)]
    public string Author { get; set; }


    public ICollection<ArticleComment> Comments { get; set; }
    public ICollection<Category> Categories { get; set; }

}

在视图模型中:

  public class ArticlesCategoriesViewModel
{

    public int Id { get; set; }
    [Required]
    public string Title { get; set; }

    [Required]
    [UIHint("tinymce_jquery_full"), AllowHtml]
    public string Body { get; set; }

    [Required]
    [DataType(DataType.Date)]
    [Display(Name = "Publication Date")]
    public DateTime DateCreated { get; set; }

    [Required]
    public string Author { get; set; }

    public IEnumerable<CategoriesViewModel> Categories { get; set; }
    public IEnumerable<CategoriesViewModel> AllCategories { get; set; }
    public string[] PostedCategories { get; set; }
}

在控制器中:

 public ActionResult Edit(int id)
    {
        //Return article with its categories
        Article articleToEdit = _repo.GetArticleCategories(id);   
        Mapper.CreateMap<Article, ArticlesCategoriesViewModel>();
        Mapper.CreateMap<Category, CategoriesViewModel>();     
        ArticlesCategoriesViewModel article = Mapper.Map<Article, ArticlesCategoriesViewModel>(articleToEdit);
        //Return all categories
        IEnumerable<Category> allCategories = _repo.GetAllCategories(); 
        IEnumerable<CategoriesViewModel> AllCategories = Mapper.Map <IEnumerable<Category>, IEnumerable<CategoriesViewModel>>(allCategories);

       article.AllCategories = AllCategories;

        if (articleToEdit == null)
        {
            return HttpNotFound();
        }

        return View(article);
    }

在视图模型中:

<ul>
    @foreach (var g in Model.AllCategories)
    {
        <li>
            <input type="checkbox" name="PostedCategories" value="@g.Id" id="@g.Id"
                 @{if (Model.Categories.FirstOrDefault(h => h.Id == g.Id) != null) { <text> checked='checked' </text>    } } />
            <label for="@g.Id">@g.Name</label>
        </li>
    }
</ul>

它可以显示文章的所有类别,但是当我提交POST时,我的新类别被选中,我的模型无效。

这是我的Post方法:

  [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,Title,Body,DateCreated,Author,PostedCategories")]ArticlesCategoriesViewModel articleToEdit)
    {

        if (ModelState.IsValid)
        {
            Mapper.CreateMap<ArticlesCategoriesViewModel, Article>();
            Article article = Mapper.Map<ArticlesCategoriesViewModel, Article>(articleToEdit);

            if (_repo.EditArticle(article) && _repo.Save())
            {
                return RedirectToAction("Index");
            }

            else
            {
                ModelState.AddModelError("", "One or more erros were found. Operation was not valid.");
                return View(articleToEdit);
            }
        }

        ModelState.AddModelError("", "One or more erros were found. Model-binding operation was not valid.");
        return View(articleToEdit);

    }

当MVC模型数据绑定尝试匹配数据时,我有空引用错误,显然是在匹配我的模型视图的集合“AllCategories”,“Categories”时。 我真的很感激任何帮助。

1 个答案:

答案 0 :(得分:2)

您应该使用Category的视图模型,该视图模型具有描述您要在视图中显示/编辑的内容的属性

public class CategoryVM
{
  public int ID { get; set; }
  public string Name { get; set; }
  public bool IsSelected { get; set; }
}

public class ArticlesCategoriesViewModel
{
  public int Id { get; set; }
  ....
  public string Author { get; set; }
  List<CategoryVM> Categories { get; set; }
}

查看

for(int i = 0; i < Model.Categories.Count; i++)
{
  @Html.CheckBoxFor(m => m.Categories[i].IsSelected)
  @Html.LabelFor(m => m.Categories[i].IsSelected, Model.Categories[i].Name)
  @Html.HiddenFor(m => m.Categories[i].ID)
  @Html.HiddenFor(m => m.Categories[i].Name)
}

在GET方法中,根据id初始化ArticlesCategoriesViewModel,并为每个可用类别添加CategoryVM,并根据已分配给文章的类别设置IsSelected属性。在POST方法中,您可以使用var selectedCategories = articleToEdit.Categories.Where(c => c.IsSelected)获取所选类别。

您还应该删除[Bind(Include="..")]属性。视图模型仅表示您在视图中显示/编辑的内容,因此不需要排除任何属性。