I'm using MVC4 and having real difficulty getting my head around where Iam going wrong. In fact I have been stuck for two weeks now. All I am trying to do is post a comment back to database using the IRepository approach. I get the following error. I was hoping someone could enlighten me on where I might be going wrong here.
No parameterless constructor defined for this object
Inherited Class on the InsertComment method Comment being my database table. So I should be able to call in that and pass in my model to update table using this apporach with ease.
public class BlogRepository : IBlogRepository, IDisposable { private BlogDataDataContext _dataContext; public BlogRepository() { _dataContext = new BlogDataDataContext(); } // #region IBlogRepository Members public IList<Entry> Posts() { var entries = from m in _dataContext.Entries select m; return entries.ToList(); } public void InsertComment(Comment comment) { _dataContext.Comments.InsertOnSubmit(comment); } public void Save() { _dataContext.SubmitChanges(); } private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { _dataContext.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // #endregion }
public class BlogController : Controller { private IBlogRepository _repository; public BlogController() : this(new BlogRepository()) { } public BlogController(IBlogRepository repository) { this._repository = repository; } public ActionResult BlogList(){ var viewModel = new ListView(_repository); return View("BlogList", viewModel); } public ActionResult BlogPost(int id, string title){ var viewModel = new ListView(_repository); ViewData["id"] = id; return View("BlogPost", viewModel); } [HttpPost] public ActionResult BlogPost(ListView model) { // CANNOT GET TO HERE WITH ERROR. if (ModelState.IsValid) { return RedirectToAction("BlogPost"); } return View(); } }
Here is my blogpost.cshtml which is where we display selected blog with comments section at the bottom. The problem is when I post the comments back to the server it should call the HTTPPOST method and then we can insertComment. I am having trouble passing the view back and cannot work out my glaring mistake.
Any advice at all would really help. I wouldn't normally post so much code but I just cant fathom it at all and think I am completely missing the point somewhere.
In my ListView Model I have a constructor like this...
public ListView(IBlogRepository blogRepository)
{
Posts = blogRepository.Posts();
}
Now I believe this is causing an issue. I dont know MVC very well and wonder what I can do with this. Maybe moving it out into the controller. Or creating another contructor for overloading with different parameters. Please help.
Thanks for your advice.