hoytdj
hoytdj

Reputation: 164

Async post model and load response with MVC

I have 2 partial views, each with their own distinct model, on a single page. I want to asynchronously post the data from one partial view (it's a form) then take the response from the controller and load it into the second partial view.

Basically my page would be structured as follows.

Parent view:

<div id="viewA">
    @Html.Partial("_viewA, Model.viewA)
</div>
<div id="viewB">
    <p>Loading...</p>
</div>

_viewA:

@model ModelA

@using (Html.BeginForm())
{
    @Html.LabelFor(model => model.Thing)
    @Html.EditorFor(model => model.Thing)
    <input type="submit" value="Submit">
}

_viewB:

@model ModelB

<table>
    <tr>
        <th>
            Column 1
        </th>
        <th>
            Column 2
        </th>
    </tr>
    @foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Col1)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Col2)
        </td>
    }
</table>

Controller:

[HttpPost]
public ActionResult Something([Bind(Include="Thing")] ModelA modela)
{
    //do stuff
    ModelB modelb = new ModelB();
    return PartialView("_viewB", modelb);
}

Javascript:

//I'm not sure...
//Probably some AJAX call
//Then we stick the response into div#viewB

The key is that I need this all to happen asynchronously. User fills out the form clicks a button, data is sent to the server, response is returned, part of the page updates, all without a post back.

What Javascript (and other changes) do I need to get this all working?

Thanks!

Upvotes: 1

Views: 5810

Answers (1)

Shyju
Shyju

Reputation: 218722

You can use ajax to submit your form and when the ajax call's response callback, update the DOM as needed.

So let's add an Id to the form element, which we can use for wiring up the ajax behavior

@using (Html.BeginForm("Something","Student",FormMethod.Post,new { id="studForm"}))
{
    @Html.LabelFor(model => model.Thing)
    @Html.EditorFor(model => model.Thing)
    <input type="submit" value="Submit">
}

Now Use this javascript to listen to the submit event, prevent the default form submit(as we are going to do an ajax post), serialize the form and send via $.post method. You can use the jQuery serialize method to get the serialized version of the form.

$(function(){

   $("#studForm").submit(function(e){
       e.preventDefault();  //prevent normal form submission

       var actionUrl = $(this).attr("action");  // get the form action value
       $.post(actionUrl ,$(this).serialize(),function(res){
          //res is the response coming from our ajax call. Use this to update DOM
          $("#viewB").html(res);
       });
   });

});

Upvotes: 5

Related Questions