render page with model after ajax post

后端 未结 2 1703
野趣味
野趣味 2021-01-14 14:52

Is it possible to make an ajax post request, and in the controller return a model, after which the page is rendered with that model? To illustrate what I mean, say we have a

相关标签:
2条回答
  • 2021-01-14 15:30

    Yes ofcourse it can be done. There are few things to keep in mind

    1) First of all the returned View after post should be a Partial View not Full View

    2) You have to put a container div on your main View where the response partial view from ajax call will be appended is success callback.

    I mean is, in your main view you will have:

    <div id="container">
    <div>
    

    and in ajax call success function append response in 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);
                 }
            })
    
    0 讨论(0)
  • 2021-01-14 15:50

    Add a success callback to your $.ajax, this will provide you with the result of the post (in this case the html), 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);
            }
        })
    

    This would be easier with a partialview rather than replacing the whole body.

    0 讨论(0)
提交回复
热议问题