如何在 jQuery $.ajax() post 请求中将模型发送到 MVC 控制器方法 [英] How to send a model in jQuery $.ajax() post request to MVC controller method
问题描述
在使用以下代码进行自动刷新时,我假设当我发帖时,模型会自动发送到控制器:
In doing an auto-refresh using the following code, I assumed that when I do a post, the model will automatically sent to the controller:
$.ajax({
url: '<%=Url.Action("ModelPage")%>',
type: "POST",
//data: ??????
success: function(result) {
$("div#updatePane").html(result);
},
complete: function() {
$('form').onsubmit({ preventDefault: function() { } });
}
});
每次有帖子都需要在model中增加value属性:
Every time there is a post, I need to increment the value attribute in the model:
public ActionResult Modelpage(MyModel model)
{
model.value = model.value + 1;
return PartialView("ModelPartialView", this.ViewData);
}
但是当页面使用 jQuery AJAX 请求发布时,模型不会传递给控制器.如何在 AJAX 请求中发送模型?
But the model is not passed to the controller when the page is posted with jQuery AJAX request. How can I send the model in the AJAX request?
推荐答案
简单的答案(在 MVC 3 以后,甚至可能是 2)是你不需要做任何特别的事情.
The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.
只要您的 JSON 参数与模型匹配,MVC 就足够聪明,可以根据您提供的参数构造一个新对象.不存在的参数只是默认的.
As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.
例如,Javascript:
For example, the Javascript:
var values =
{
"Name": "Chris",
"Color": "Green"
}
$.post("@Url.Action("Update")",values,function(data)
{
// do stuff;
});
模型:
public class UserModel
{
public string Name { get;set; }
public string Color { get;set; }
public IEnumerable<string> Contacts { get;set; }
}
控制器:
public ActionResult Update(UserModel model)
{
// do something with the model
return Json(new { success = true });
}
这篇关于如何在 jQuery $.ajax() post 请求中将模型发送到 MVC 控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!