在ajax发布后使用模型渲染页面 [英] render page with model after ajax post

查看:82
本文介绍了在ajax发布后使用模型渲染页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以发出ajax发布请求,并在控制器中返回一个模型,然后用该模型呈现页面?为了说明我的意思,请说我们有一个简单的ajax帖子:

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 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 the Home Controller I have:

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

我该如何实现?目前,此操作不执行任何操作,该页面不会刷新或自身重新呈现.是否可以通过ajax请求执行此操作?

How do I achieve this? At the moment, this does nothing, the page doesn't refresh or re-render itself. Is it possible to do this from an ajax request?

我使用ajax而不使用模型来绑定表单数据的原因是因为它是动态的,并且据我所知我无法将表单数据动态绑定到模型.

The reason I am using ajax but not using a model to bind the form data is because it's dynamic and as I understand I cannot dynamically bind form data to the model.

推荐答案

$.ajax中添加success回调,这将为您提供发布的结果(在本例中为html),例如:

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.

这篇关于在ajax发布后使用模型渲染页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆