Jason
Jason

Reputation: 11615

MVC3 Unobtrusive Ajax - Partial View Not Reflecting Model

Everything appears to work as expected except that when it returns back the Partial with the model that has NAME = "foo" after it has inserted the object, it does not change the Name and PercentAlcohol text boxes with the values in the Model.

When I output @Model.Name in the header of the partial by the validation messages it properly shows "foo". But the form still says whatever was in the textboxes when it was submitted.

HTML

<div id="createBeerForm">
    @{Html.RenderPartial("CreatePartial", new BeerCreateModel());}
</div>

CreatePartial

@{
    AjaxOptions options = new AjaxOptions
    {
        HttpMethod = "Post",
        UpdateTargetId = "createBeerForm", 
        InsertionMode = InsertionMode.Replace
    };        
}

@using (Ajax.BeginForm("Create", "Beer", null, options, new { @class = "form-stacked" }))
{
    @Html.ValidationSummary(true, "You have errors. Fix them.")
    @Html.LabelFor(m => m.Name)
    <div>
        @Html.TextBoxFor(m => m.Name, new { @class = "xlarge" })  
        @Html.ValidationMessageFor(m => m.Name)
    </div>
    @Html.LabelFor(m => m.PercentAlcohol)
    <div>
        @Html.TextBoxFor(m => m.PercentAlcohol, new { @class = "xlarge" }) 
        @Html.ValidationMessageFor(m => m.PercentAlcohol)
    </div>
    <p>
        <input type="submit" value="Create Beer" />
    </p>
}

Controller

    [HttpPost]
    public ActionResult Create(BeerCreateModel model)
    {
        if (ModelState.IsValid)
        {
            //Add Beer to DB
            return PartialView("CreatePartial", new BeerCreateModel { Name = "foo"});
        }
        else
        {
            return PartialView("CreatePartial", model);
        }
    }

Upvotes: 1

Views: 890

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039538

You must clear the modelstate if you intend to change values in your POST controller action. HTML helpers first look at the modelstate when binding and then at the model. So:

[HttpPost]
public ActionResult Create(BeerCreateModel model)
{
    if (ModelState.IsValid)
    {
        //Add Beer to DB

        // Here you are modifying the value of the Name parameter
        // in your model. But this parameter is also in ModelState.
        // So if you want this change to reflect on the subsequent view you
        // need to either clear it from the modelstate
        ModelState.Remove("Name");
        return PartialView("CreatePartial", new BeerCreateModel { Name = "foo"});
    }
    else
    {
        return PartialView("CreatePartial", model);
    }
}

Upvotes: 3

Related Questions