jquery - ajax post后使用模型渲染页面

标签 jquery ajax asp.net-mvc

是否可以发出 ajax post 请求,并在 Controller 中返回一个模型,然后使用该模型渲染页面?为了说明我的意思,假设我们有一个简单的 ajax 帖子:

$.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
    }
})

在家庭 Controller 中我有:

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

我该如何实现这一目标?目前,这没有任何作用,页面不会刷新或重新渲染自身。是否可以通过 ajax 请求来执行此操作?

我使用ajax但不使用模型来绑定(bind)表单数据的原因是因为它是动态的,据我所知,我无法将表单数据动态绑定(bind)到模型。

最佳答案

向您的 $.ajax 添加一个 success 回调,这将为您提供帖子的结果(在本例中为 html),如下所示:

    $.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);
        }
    })

使用局部 View 比替换整个主体更容易。

关于jquery - ajax post后使用模型渲染页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30592702/

相关文章:

javascript - JQuery AJAX 和 OOP JS 作用域问题

c# - 在 ASP.NET MVC 3 中使用 ASP.NET Membership e Profile

javascript - 单击链接时使用 AJAX 在 Kendo 窗口中加载数据

javascript - Jquery 图像预览并仍然保留在提交时?

javascript - 关于取消 Twitter Bootstrap 警报的 Ajax 请求

c# - 在我的 ASP.NET 应用程序中的什么地方注册 IMemoryCache?

javascript - 单击父div时如何在 anchor 上触发单击事件

javascript - 流式不起作用?

javascript - jquery html() 不设置 div 内容

javascript - 尝试加载本地 json 文件,但无法在外部范围中读取它