I am trying to teach myself C# and MVC 3.
I am learning by creating a simple blog application. I am stuck at detail page of the blog. This page displays the post and it works fine – that is, displays the post and the comments on the post. However, I want to add a form to add new comments.
I think the way to do that is to create a viewmodel which contains both blog and comment class and then I should be able to create a comment form which calls create action of comment controller.
However, when I do that the blog display page doesnt show up becasue it expects a model of type ‘BlogDetailViewModel’. I guess that is because the ‘Details’ action of ‘Blog’ controller is passing a ‘blog’ model to the view and not ‘BlogDetailViewModel’. How do I correct this error.
Is this the best way to deal with this issue.
I am detailing all the code below:
Blog Controller – Details Method
public ViewResult Details(int id)
{
Blog blog = db.Blogs.Find(id);
return View(blog);
}
Blog.cs
public class Blog
{
public int BlogID { get; set; }
public string Title { get; set; }
public string Writer { get; set; }
[DataType(DataType.MultilineText)]
public string Excerpt { get; set; }
[DataType(DataType.MultilineText)]
public string Content { get; set; }
[DataType(DataType.Date)]
public DateTime PublishDate { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
Comment.cs
public class Comment
{
public int CommentID { get; set; }
public string Name { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[DataType(DataType.MultilineText)]
public string CommentBody { get; set; }
public int BlogID { get; set; }
public virtual Blog Blog { get; set; }
}
BlogDetailViewModel.cs
public BlogDetailViewModel
{
public Blog Blog{ get; set; }
public Comment comment{ get; set; }
}
Blog Details View
@model NPLHBlog.ViewModels.BlogDetailViewModel
@{
ViewBag.Title = @Model.Blog.Title;
}
….
I have tried to comment everything out of blog details view and just keep the title. However, even that doesn’t work.
Any help would be grateful.
The type passed to
View()in your controller must match the@modeltype in your view.