Asp.net mvc 如何将项目添加到模型';s ICollection列表属性
我有类似的东西Asp.net mvc 如何将项目添加到模型';s ICollection列表属性,asp.net-mvc,linq,entity-framework-4,Asp.net Mvc,Linq,Entity Framework 4,我有类似的东西 [HttpPost] public ActionResult CreatePost(Post post) { var categoryList = Request["CategoryList"].Split(','); //I want to set my Category Name in here foreach (var category in categoryList) { post.Categories.Add(new
[HttpPost]
public ActionResult CreatePost(Post post)
{
var categoryList = Request["CategoryList"].Split(',');
//I want to set my Category Name in here
foreach (var category in categoryList)
{
post.Categories.Add(new Category { Name = category });
}
post.CreatedDate = DateTime.Now;
post.CreatedBy = _userService.GetCurrentUser().Id;
_postService.CreatePost(post);
return View();
}
我想设置
公共虚拟ICollection类别{get;set;}
这是在我的Post模型中。它有两个属性Id
和Name
。我想像上面那样在我的CreatePost
方法中设置我的属性。我应该怎么做?这里是我如何解决问题而不在ActionResult
方法中创建实例的方法
我刚刚在模型构造函数中创建了一个实例
public Post()
{
this.Categories = new HashSet<Category>();
}
public Post()
{
this.Categories=newhashset();
}
这是正确的解决方案。就是看不到问题所在?对象引用未设置为对象的实例。我通过添加这个来解决这个错误。类别=新列表();但是为什么要创建新实例呢?可能是