Updating View with Model changes via Ajax Post - MVC3

You can update the view, just not the model. The model in a razor page is compiled on the server in order to render the view; you would need to recompile the razor page after every ajax request.

Only real option is to return json from server and manually update DOM/View.


First thing in the jQuery the proper way to set a value of an input is to use:

$("#Str").val(@Model.Str);

Next we'll look at the controller. In the POST action result you are returning the entire View in your AJAX call. That means all the HTML, script references, and JavaScript are being returned in your jQuery post request. Since all you are trying to update is the value of the input named Str, I would just return that value as JSON and nothing else.

[HttpPost]
public ActionResult ChangeTheValue(MyModel model)
{
    var m = new MyModel();
    m.Str = model.Str;
    m.Str = m.Str + " Changed! ";
    m.Integer++;

    return Json(m.Str);

}

Next I would place your HTML inputs in a <form> so you can have jQuery serialize your model for you and then you can change your jQuery post code to be:

function changeButtonClicked() {
    var url = '@Url.Action("ChangeTheValue", "Test1")';
    $.post(url, $('form').serialize(), function (view) {
        $("#Str").val(view);
    });
}

All the serialization is doing is encoding the inputs in your form into a string and if everything is named properly ASP.NET will bind that back to your model.

If you need to have your route handle both AJAX calls and full requests you could use ASP.NET's IsAjaxRequest function to test the request and return different results depending on if the request is AJAX or not. You would do something like this in your controller:

[HttpPost]
public ActionResult ChangeTheValue(MyModel model)
{
    var m = new MyModel();
    m.Str = model.Str;
    m.Str = m.Str + " Changed! ";
    m.Integer++;

    if (Request.IsAjaxRequest) {
        return Json(m.Str);
    }
    else {
        return View("Test1", m);
    }
}

In the ActionResult above you are doing everything you did before, but now are testing the request type and if it's AJAX you return a JSON result of your string value. If the request was not from an AJAX call then the full View (HTML, scripts, etc) are returned to be displayed in the browser.

I hope this is helps you out and is what you were looking for.