Ben Ford
Ben Ford

Reputation: 1394

Form in Partial not binding to model

I've got a page basically displaying an article backed by a database.

Below that article, there is a comments section. This is provided by a @Html.Action call returning a _Comments partial.

Within that _Comments partial. There is an optional _AddComment @Html.Action call that renders a _AddComment partial within it.

The _AddComment partial is backed by _AddComment controller methods for GET and POST.

[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult _AddComment(EditComment comment)

The GET method just returns an "EditComment" VM with the AssetID attached.

Whenever a comment is filled in and posted within the _AddComment view. It's controller method is called correctly, but the model isn't passed back.

If I look at the Request parameters I can see all the properties of the model being passed back correctly. However, it's not being bound into the Controllers method parameter.

I've tried specifying "Model" as the route params for the Html.Begin form. It's made no difference.

Have looked at a number of SO posts, none of which sort the issue I'm having!

Presumably the model binding is failing somewhere for some reason. But obviously without an exception I've no idea what's wrong!

View Model Code

public class EditComment
{
    public Boolean HasRating { get; set; }
    public int AssetID { get; set; }
    public int CommentID { get; set; }
    public int Rating { get; set; }
    public string Comment { get; set; }
}

View Code

@model SEISMatch.UI.Models.Content.EditComment

<hr />

<h3><span class="colored">///</span> Leave a Comment</h3>

<div class="row" style="margin-top: 20px;">
    @using (Html.BeginForm("_AddComment", "Content", Model, FormMethod.Post))
    {    
        @Html.ValidationSummary(false)
        @Html.AntiForgeryToken()
        @Html.HiddenFor(m => m.AssetID)
        @Html.HiddenFor(m => m.CommentID)

        if (Model.HasRating)
        {
            @Html.EditorFor(m => m.Rating, "_StarRating")
        }

        <div class="span7">
            @Html.TextAreaFor(m => m.Comment, new { @class = "span7", placeholder = "Comment", rows = "5" })
        </div>
        <div class="span7 center">
            <button type="submit" class="btn btn-success">Post comment</button>
        </div>
    }
</div>

Upvotes: 0

Views: 154

Answers (1)

maxlego
maxlego

Reputation: 4914

Your action parameter name is comment and class EditComment has Property Comment. Modelbinder gets confused.

Rename your action parameter and problem solved.

[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult _AddComment(EditComment model)

Upvotes: 1

Related Questions