I'm new to ASP.NET MVC, and I'm trying to create a very simple blog type site as a way to find out how everything works. But I had a problem sending from the comment form to the model, which is null, and I can not say why.
On the blog page, I have a โadd commentโ link that calls some jQuery to display a partial view that is strongly typed in CommentModel. The link also goes through the identifier of the blog post, and the partial one is encoded as follows:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Blog.Models.CommentModel>" %> <% using (Html.BeginForm()) { %> <%: Html.HiddenFor(x => x.Post.ID) %> <%: Html.HiddenFor(x => x.CommentID) %> <%: Html.TextBoxFor(x => x.Name) %><br /> <%: Html.TextBoxFor(x => x.Email) %><br /> <%: Html.TextBoxFor(x => x.Website) %><br /> <%: Html.TextAreaFor(x => x.Comment) %><br /> <input type="submit" value="submit" /> <% } %>
CommentsModel is simple and looks like this (I havenโt applied any validations yet or something else):
public class CommentModel { public BlogPost Post { get; set; } public int CommentID { get; set; } public string Name { get; set; } public string Email { get; set; } public string Website { get; set; } public string Comment { get; set; } }
Then it is supposed to send a message to a simple controller action, which will add a comment to the database and return the user to the page. For simplicity, I deleted most of the code, but it looks like:
[HttpPost] public ActionResult CommentForm(CommentModel model) { if (ModelState.IsValid) { } else { } }
Everything works as expected, except that when the comment form is published, the comment model is NULL. I cannot understand why this is null. When I look at the source of the partial view, I see that "Post.ID" is filled with the correct identifier, but this is lost when the form is submitted.
Did I miss something obvious here? I created forms like this in the past and it worked fine, I canโt understand why its not now. Thanks in advance.
Later Edit:
I typed the code incorrectly and changed the public ActionResult CommentForm(CommentModel model) from the public ActionResult CommentForm(CommentModel comment) , which caused the problem.
Thanks for the help.