如何在 jQuery $.ajax() post 请求中将模型发送到 MVC 控制器方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1518417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send a model in jQuery $.ajax() post request to MVC controller method
提问by ravikiran
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() { } });
}
});
Every time there is a post, I need to increment the value attribute in the model:
每次有帖子,我都需要增加模型中的value属性:
public ActionResult Modelpage(MyModel model)
{
model.value = model.value + 1;
return PartialView("ModelPartialView", this.ViewData);
}
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?
但是当页面使用 jQuery AJAX 请求发布时,模型不会传递给控制器。如何在 AJAX 请求中发送模型?
回答by Chris S
The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.
简单的答案(在 MVC 3 之后,甚至可能是 2)是您不必做任何特别的事情。
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.
只要您的 JSON 参数与模型匹配,MVC 就足够聪明,可以根据您提供的参数构造一个新对象。不存在的参数只是默认的。
For example, the Javascript:
例如,Javascript:
var values =
{
"Name": "Chris",
"Color": "Green"
}
$.post("@Url.Action("Update")",values,function(data)
{
// do stuff;
});
The model:
该模型:
public class UserModel
{
public string Name { get;set; }
public string Color { get;set; }
public IEnumerable<string> Contacts { get;set; }
}
The controller:
控制器:
public ActionResult Update(UserModel model)
{
// do something with the model
return Json(new { success = true });
}
回答by Laviak
If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.
如果您需要将完整模型发送到控制器,您首先需要该模型可用于您的 javascript 代码。
In our app, we do this with an extension method:
在我们的应用程序中,我们使用扩展方法执行此操作:
public static class JsonExtensions
{
public static string ToJson(this Object obj)
{
return new JavaScriptSerializer().Serialize(obj);
}
}
On the view, we use it to render the model:
在视图上,我们使用它来渲染模型:
<script type="javascript">
var model = <%= Model.ToJson() %>
</script>
You can then pass the model variable into your $.ajax call.
然后您可以将模型变量传递到您的 $.ajax 调用中。
回答by dano
I have an MVC page that submits JSON of selected values from a group of radio buttons.
我有一个 MVC 页面,它从一组单选按钮提交选定值的 JSON。
I use:
我用:
var dataArray = $.makeArray($("input[type=radio]").serializeArray());
To make an array of their names and values. Then I convert it to JSON with:
制作它们的名称和值的数组。然后我将其转换为 JSON:
var json = $.toJSON(dataArray)
and then post it with jQuery's ajax() to the MVC controller
然后将其与 jQuery 的 ajax() 一起发布到 MVC 控制器
$.ajax({
url: "/Rounding.aspx/Round/" + $("#OfferId").val(),
type: 'POST',
dataType: 'html',
data: json,
contentType: 'application/json; charset=utf-8',
beforeSend: doSubmitBeforeSend,
complete: doSubmitComplete,
success: doSubmitSuccess});
Which sends the data across as native JSON data.
它将数据作为本机 JSON 数据发送。
You can then capture the response stream and de-serialize it into the native C#/VB.net object and manipulate it in your controller.
然后,您可以捕获响应流并将其反序列化为本机 C#/VB.net 对象并在您的控制器中对其进行操作。
To automate this process in a lovely, low maintenance way, I advise reading this entry that spells out most of native, automatic JSON de-serialization quite well.
为了以一种可爱的、低维护的方式自动化这个过程,我建议阅读这篇文章,它很好地说明了大部分原生的、自动的 JSON 反序列化。
Match your JSON object to match your model and the linked process below should automatically deserialize the data into your controller. It's works wonderfully for me.
匹配您的 JSON 对象以匹配您的模型,下面的链接过程应该会自动将数据反序列化到您的控制器中。它对我来说非常有效。
回答by logan gilley
This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.
这可以通过构建一个 javascript 对象来匹配您的 mvc 模型来完成。javascript 属性的名称必须与 mvc 模型完全匹配,否则自动绑定不会在帖子中发生。在服务器端拥有模型后,您就可以对其进行操作并将数据存储到数据库中。
I am achieving this either by a double click event on a grid row or click event on a button of some sort.
我通过网格行上的双击事件或某种按钮上的单击事件来实现这一点。
@model TestProject.Models.TestModel
<script>
function testButton_Click(){
var javaModel ={
ModelId: '@Model.TestId',
CreatedDate: '@Model.CreatedDate.ToShortDateString()',
TestDescription: '@Model.TestDescription',
//Here I am using a Kendo editor and I want to bind the text value to my javascript
//object. This may be different for you depending on what controls you use.
TestStatus: ($('#StatusTextBox'))[0].value,
TestType: '@Model.TestType'
}
//Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox
//selected value. This puzzled me due to the conversion to Json object in the Ajax call.
//By parsing the Type to an int this worked.
javaModel.TestType = parseInt(javaModel.TestType);
$.ajax({
//This is where you want to post to.
url:'@Url.Action("TestModelUpdate","TestController")',
async:true,
type:"POST",
contentType: 'application/json',
dataType:"json",
data: JSON.stringify(javaModel)
});
}
</script>
//This is your controller action on the server, and it will autobind your values
//to the newTestModel on post.
[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
TestModel.UpdateTestModel(newTestModel);
return //do some return action;
}
回答by rajesh pillai
I think you need to explicitly pass the data attribute. One way to do this is to use the data = $('#your-form-id').serialize();
我认为您需要明确传递数据属性。一种方法是使用 data = $('#your-form-id').serialize();
This post may be helpful. Post with jquery and ajax
这篇文章可能会有所帮助。 使用 jquery 和 ajax 发布
Have a look at the doc here.. Ajax serialize
看看这里的文档.. Ajax 序列化
回答by Majid Hosseini
you can create a variable and send to ajax.
您可以创建一个变量并发送到ajax。
var m = { "Value": @Model.Value }
$.ajax({
url: '<%=Url.Action("ModelPage")%>',
type: "POST",
data: m,
success: function(result) {
$("div#updatePane").html(result);
},
complete: function() {
$('form').onsubmit({ preventDefault: function() { } });
}
});
All of model's field must bo ceated in m.
模型的所有字段都必须以米为单位。
回答by Sarang Raotole
In ajax call mention-
在ajax调用中提到-
data:MakeModel(),
use the below function to bind data to model
使用以下函数将数据绑定到模型
function MakeModel() {
var MyModel = {};
MyModel.value = $('#input element id').val() or your value;
return JSON.stringify(MyModel);
}
Attach [HttpPost] attribute to your controller action
将 [HttpPost] 属性附加到您的控制器操作
on POST this data will get available
在 POST 时,此数据将可用