【问题标题】:How to add item to Model's ICollection List Property如何将项目添加到模型的 ICollection 列表属性
【发布时间】:2015-09-30 23:45:17
【问题描述】:

我有这样的事情

[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();
}

我想在我的帖子模型中设置public virtual ICollection<Category> Categories { get; set; }this。它有两个属性IdName。我想在上面的CreatePost 方法中设置我的属性。我该怎么做?

【问题讨论】:

  • 只是看不出问题出在哪里?
  • 对象引用未设置为对象的实例。我得到了这个错误它通过添加这个来解决。类别 = 新列表();但是为什么要创建新实例呢?

标签: asp.net-mvc linq entity-framework-4


【解决方案1】:

这就是我如何在ActionResult 方法中不创建实例就解决了我的问题

我刚刚在模型构造函数中创建了实例。

  public Post()
        {
            this.Categories = new HashSet<Category>();
        }

这是正确的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-13
    • 2012-05-23
    • 2014-01-06
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    相关资源
    最近更新 更多