[英]CheckBoxList for many-to-many relationship in ASP.NET MVC
I am trying to implement a check box list in MVC for a many-to-many relationship (Article - Category). 我正在尝试在MVC中实现多对多关系(文章-类别)的复选框列表。 I have tried this, but I does not work.
我已经尝试过了,但是没有用。 Does anybody know a different and properly approach to get it.
是否有人知道采用其他合适的方法来获得它。
In the domain model: 在域模型中:
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; }
}
In the View Model: 在视图模型中:
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; }
}
In the controller: 在控制器中:
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);
}
In the view model: 在视图模型中:
<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>
It works to show all the categories of the article, but when I Submit to POST my new categories selected, my model is not valid. 它可以显示文章的所有类别,但是当我提交POST到我的新类别时,我的模型无效。
This is my Post method: 这是我的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);
}
I have got null references error when MVC model-data-binding try to match the data, apparently happens when it is matching the collections "AllCategories", "Categories" of my model view. 当MVC模型数据绑定试图匹配数据时,出现空引用错误,显然是当它与我的模型视图的“ AllCategories”,“ Categories”集合匹配时发生。 I would really appreciate any help.
我真的很感谢您的帮助。
You should use a view model for Category
which has properties that describe what you want to display/edit in the view 您应该对
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; }
}
View 视图
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)
}
In the GET method, initialize the ArticlesCategoriesViewModel
based on the id, and add a CategoryVM for each available category and set the IsSelected property based on the categories already assigned to the Article. 在GET方法中,基于id初始化
ArticlesCategoriesViewModel
,并为每个可用类别添加CategoryVM,并基于已分配给Article的类别设置IsSelected属性。 The in the POST method, you can get the selected categories with var selectedCategories = articleToEdit.Categories.Where(c => c.IsSelected)
. 在POST方法中,您可以使用
var selectedCategories = articleToEdit.Categories.Where(c => c.IsSelected)
来获取选定的类别。
You should also remove the [Bind(Include="..")]
attribute. 您还应该删除
[Bind(Include="..")]
属性。 A view model represents only what you display/edit in a view so it is unnecessary since you should not be excluding any properties. 视图模型仅代表您在视图中显示/编辑的内容,因此这是不必要的,因为您不应排除任何属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.