是否可以发出 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/