Reputation: 2711
Im creating a simple blog using MVC and entity framework.
These are my two classes:
public class BlogPost
{
public int BlogPostID { get; set; }
public string Title { get; set; }
public string Post { get; set; }
public DateTime Date { get; set; }
public virtual ICollection<Comments> Comments { get; set; }
}
public class Comments
{
public int CommentsID { get; set; }
public string Comment { get; set; }
public string Author { get; set; }
public DateTime Date { get; set; }
public int BlogPostID { get; set; }
}
Now, in my view, I display a Blogpost and i would like the user to be able to leave a comment, I imagin that the best way to do this is to create a beginform. This is what i have got:
@using (Html.BeginForm("AddComment", "BlogPosts", new { blogid = @Model.BlogPostID }, FormMethod.Post))
{
@Html.TextBoxFor() <---How do i acess the "Author"-property in comments?
@Html.TextAreaFor() <---How do i acess the "Comment"-property in comments?
<button type="submit">Add Comment</button>
}
When the above problems are sorted out i´ll use this method to add the comment to the db:
public ActionResult AddComment(int blogid, Comments model)
{
BlogPost blogPost = db.BlogPosts.Find(blogid);
blogPost.Comments.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
Does this seem like a good way to go about a task like this or am i maybe missing something fundamental? Thans!
Upvotes: 0
Views: 158
Reputation: 4621
Create a Partial view for adding comment the model for partial view will be Comments type
Now put below razor in your partial view
@model Comments
@using (Html.BeginForm("AddComment", "BlogPosts", new { blogid = @Model.BlogPostID }, FormMethod.Post))
{
@Html.TextBoxFor(model=>model.Author)
@Html.TextAreaFor(model=>model.Comment)
<button type="submit">Add Comment</button>
}
Lets call this partial view AddComment.cshtml
Now in the blog post view add this partial view at the bottom like ,
@Html.Partial("AddComment",new Comments())
Upvotes: 1