在ajax发布后使用模型渲染页面 [英] render page with model after ajax post
问题描述
是否可以发出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屋!