Ad

Asp.Net MVC Ajax View Model Not Updated

- 1 answer

I have a problem that is doing my head in

Say I have a view model

public class PersonVM 
{
    public int? Id { get; set; }            

    public string Firstname { get; set; }
}

And now I have a view which has a single input box which captures the Firstname only.

@model PersonVM

<form id="frmCreatePerson">
    @Html.Bootstrap().TextBoxFor(p => p.Firstname).Placeholder("Firstname")

    @Html.Bootstrap().Button().Id("btnSubmit").Text("Create").AppendIcon("fa fa-arrow-right")
</form>

@{
if(Model.Id != null) 
{
    Html.Partial("_Results", Model)
}
}

I have an Ajax call to the controller to just generate a new Id for the view model.

Then after that I want the updated view model to be displayed.

$('#btnSubmit').click(function () {

    var data = $("#frmCreatePerson").serialize();

    $.ajax({
        url: '@Url.Action("CreatePerson", "Person")',
        type: "POST",
        data: data
    })
      .done(function (data) {


      })
      .fail(function () {
          alert("Unable to create.");
      });
});

Controller

[HttpPost]
public ActionResult CreatePerson(PersonVM model)
{
    model.id = 1;

    return PartialView("_Results", model);
}

The _Results partial view just contains

@model PersonVM

@Html.DisplayForModel(Model);

For some reason the view model is not updated and the model is still empty. How can I submit an Ajax call to the controller and return an updated view model to the controller to be displayed back?

Is this even possible without page reload (A.K.A standard action link)?

Ad

Answer

You need to basically use the response coming back (The rendered markup of the partial view) to your DOM. So first create a container div in your page.

<div id="items"></div>

and in your done event of the ajax method, append the response to this div.

$('#btnSubmit').click(function () {

    var data = $("#frmCreatePerson").serialize();

    $.ajax({
        url: '@Url.Action("CreatePerson", "Person")',
        type: "POST",
        data: data
    })
    .done(function (data) {

         $("#items").append(data); // append the response to DOM

    })
    .fail(function () {
          alert("Unable to create.");
    });
});
Ad
source: stackoverflow.com
Ad