Can't understand why the model is null for postback?

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.

+4
source share
2 answers

A similar question was asked yesterday. Check: MVC3 - Insert using ViewModel - Object reference not installed in object instance

The problem that I see is that when submitting the form, Post.ID and CommentID are sent, while your action expects a completely deflated object of type "CommentModel". The model binder cannot map message data to the corresponding model object.

+6
source

Add

 public int PostID {get; set;} 

... to your model and fill this in your controller as a hidden input. The Post object will not be easy to parse.

0
source

Source: https://habr.com/ru/post/1379859/


All Articles