Michael McCarthy
Michael McCarthy

Reputation: 1542

How to return a view from a partial view post to a Controller?

So I have a partial view "_Customer "with a text box and a save button. Currently, the partial view code, I have this:

@model CompositeViews.Models.Customer

@using (Ajax.BeginForm("Edit", "Customer", new AjaxOptions { HttpMethod = "Post",     InsertionMode = InsertionMode.Replace, UpdateTargetId = "customerDiv" }))
{
<div id="customerDiv">
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Customer</legend>

        @Html.HiddenFor(model => model.CustomerId)

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <p><input type="submit" value="Save" /></p>
    </fieldset>
</div>
}

the view lives withing a parent view called index (which also provides the model the partial view is dependent upon):

@model CompositeViews.ViewModels.CompositeViewModel
<h2>Index</h2>
@Html.Partial("_Customer", Model.Customer)

The parent view is named Index.cshtml and is fed by a simple controller action. When I click on the Save button in the partial view, it goes to the appropriate action on the appropriate controller, but I'm not too sure how to return the updated model data BACK into the partial view.

In all the examples out there, it's a form that does an async post, but the UpdateTargetId targets a that is then filled with some type of updated content. That seems pretty straight-forward and simple.

What I'm struggling with is how to return the same form, with the updated model information using the existing view (_Customer). Basically, it's a BeginForm which targets itself with the result from the controller action, not some other div that is not part of the form.

I'd like to NOT have to rebuild all the HTML by hand that the _Customer view does for me via the MVC framework and return that for rendering. I guess I'm stuck with the form in the partial view submitting the data to the controller, and then needing a way for that same view to re-draw itself on returning from the action method.

Any ideas?

Upvotes: 0

Views: 1485

Answers (1)

Dima
Dima

Reputation: 6741

I hope I got you right and you want to show your updated on post back. In that case you can try this:

<div id="customerDiv">
  @Html.RenderAction("Edit", "Customer", Model)
</div>

and put your @using (Ajax.BeginForm()) in Edit result.

Upvotes: 1

Related Questions