0

I have something like this

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

I want to set public virtual ICollection<Category> Categories { get; set; }this is in my Post Model. It has two properties Id and Name. I want to set my property in my CreatePost method like above. How should I do that?

sercanD
  • 187
  • 1
  • 13
  • just can't see where your problem is? – teo van kot Jul 12 '15 at 19:11
  • Object reference not set to an instance of an object. I got this error Its solving by adding this. Categories = new List(); but why should create new instance ? – sercanD Jul 12 '15 at 19:19
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Zabavsky Jul 12 '15 at 19:19

1 Answers1

0

Here it is how i solved my problem without create a instance in my ActionResult method

I just created instance in Model constructor.

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

And this is the right solution for do that.

sercanD
  • 187
  • 1
  • 13