Make page with model after ajax post

Is it possible to make an ajax post request and return a model in the controller, after which the page will be rendered using this model? To illustrate what I mean, let's say we have a simple ajax post:

$.ajax({
    url: "/Home/PostReq",
    data: JSON.stringify(data),
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    dataType: "html",
    cache: false,
    async: true,
    error: function (jqXHR, error, errorThrown) {
        //display error
    }
})

      

And in Home Controller I have:

[HttpPost]
public ActionResult PostReq(MyModel model)
{ 
    //do some changes to model
    //render view with new model
    return View(model);
}

      

How can I achieve this? At the moment this does nothing, the page is not refreshed or re-rendered itself. Is it possible to do this from an ajax request?

I am using ajax but not using the model to bind the form data because it is dynamic and as far as I understand I cannot dynamically bind the form data to the model.

+3


source to share


2 answers


Add a callback success

to yours $.ajax

, this will give you the result of the post (html in this case), something like:

    $.ajax({
        url: "/Home/PostReq",
        data: JSON.stringify(data),
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        dataType: "html",
        cache: false,
        async: true,
        error: function (jqXHR, error, errorThrown) {
            //display error
        },
        success: function (data, textStatus, jqXHR) {
            $("body").html(data);
        }
    })

      



It would be easier with a partial view rather than a full body replacement.

+3


source


Yes, of course it can be done. There are a few things to keep in mind.

1) First of all, the returned View after post must be a partial view, not complete.

2) . You have to put a container div in your main view where the partial view of the response from the ajax call will be added - this is a successful callback.

I mean, in your main view, you would have:



<div id="container">
<div>

      

and in the success function of the ajax call add the response to the container div like:

$.ajax({
            url: "/Home/PostReq",
            data: JSON.stringify(data),
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            async: true,
            error: function (jqXHR, error, errorThrown) {
                //display error
            }
            success: function(response) {

              $('#container').html(response);
             }
        })

      

+2


source







All Articles