Thursday, September 13, 2012

Learning MVC: No parameterless constructor defined for this object

I'm developing a sample application using MVC - a "blog engine". OK, getting rid of all the buzzwords, it is just a few tables: Blogs, Bloggers, Posts. You can add bloggers, create blogs and add posts to a selected blog. Being a good boy, I'm trying not to pass objects like Blog or Post to the view, but rather use ViewModels wherever makes sense. Nothing complicated, for example

public class BlogViewModel
{
 public Blog Blog;
 public List<Post> Posts;
 ...
 
 public BlogViewModel(Blog blog, List<Post> posts, ... )
 {
  Blog = blog;
  Posts = posts;
  ...
 }
}

and then in the BlogController I would have these methods for creating a new blog:

public ActionResult Create()
{
 Blogger selectedBlogger = db.Bloggers.First();
 Blog blog = new Blog();
 return View(new BlogViewModel(blog, new List<Post>(), ...));
}

[HttpPost]
public ActionResult Create(BlogViewModel viewModel)
{
 Blog blog = viewModel.Blog;
 blog.Blogger = db.Bloggers.Where(b => b.BloggerID == viewModel.BloggerID).FirstOrDefault();

 if (ModelState.IsValid)
 {
  try
  {
   db.Blogs.Add(blog);
   db.SaveChanges();
  }
  
  // process errors
 }
 return View(new BlogViewModel(blog, new List<Post>(), ...));
}

Something like that. So I'm testing the create method when I suddenly recieve the "No parameterless constructor defined for this object" error.

No parameterless constructor defined for this object

That left me scratching my head for some time, because I could not figure out what constructor I'm missing. Took a bit of searching to realise: the constructor is missing in the ViewModel. If I modify the constructor shown above as follows

public class BlogViewModel
{
 public Blog Blog;
 public List<Post> Posts;
 ...
 
 public BlogViewModel()
 { 
 }

 public BlogViewModel(Blog blog, List<Post> posts, List<Blog> blogs, int bloggerid, List<Blogger> bloggers)
 {
  Blog = blog;
  Posts = posts;
  ...
 }
}

the error just goes away (notice that parameterless constructor that is just sitting there now, happily doing nothing?). Why is that? Well, I'll be totally honest: I have no idea.

Reference

Fun and Struggles with MVC – No Parameterless Constructor Defined by . Also posted on my website

1 comment:

Unknown said...

You saved my day man,great.Thanks for sharing