[英]How to pass a javascript object to a C# MVC 4 controller
In MVC4, how do you pass a javascript object to a C# controller in AJAX? 在MVC4中,如何将javascript对象传递给AJAX中的C#控制器? Finally I tried this but it did not work.
最后,我尝试了一下,但没有成功。
Javascript Client side: Javascript客户端:
var myData = {Propr1: '', Propr2: ''};
$.ajax({
type: 'POST',
data: JSON.stringify(myData),
url: '/Home/SubmitMyData',
contentType: 'application/json',
dataType: 'json',
success: alert('Youhou'),
error: alert('not good')
});
C# Server side method: C#服务器端方法:
public ActionResult SubmitMyData(MyParamModel myParam)
{
// Do my stuff here with my parameter
return View();
}
public class MyParamModel
{
string Prop1 { get; set; }
string Prop2 { get; set; }
}
My parameter is always null. 我的参数始终为null。 I tried to change the contentType but it still not work.
我试图更改contentType,但仍然无法正常工作。 Where are my mistakes?
我的错误在哪里? I found some posts but I did not find what I did wrong.
我找到了一些帖子,但没有发现我做错了什么。
Thanks a lot. 非常感谢。
Propr1
and Propr2
for the javascript object, but in the C# model you had Prop1
and Prop2
(missing the "r"). Propr1
和Propr2
,但是在C#模型中,您具有Prop1
和Prop2
(缺少“ r”)。 stringify
the data before sending it, and do not set dataType
to json
. stringify
处理,也不要将dataType
设置为json
。 MVC can parse just fine with a collection of post parameters without the json serialization in your code. contentType
, it is not necessary. contentType
,这是没有必要的。 WebAPI should autodetect this. Javascript Client side: Javascript客户端:
var myData = {Prop1: '', Prop2: ''}; // #1
$.ajax({
type: 'POST',
data: myData, // #2
url: '/Home/SubmitMyData',
//contentType: 'application/json', #3
//dataType: 'json', #2
success: alert('Youhou'),
error: alert('not good')
});
C# Server side method: C#服务器端方法:
public ActionResult SubmitMyData(MyParamModel myParam)
{
// Do my stuff here with my parameter
return View();
}
public class MyParamModel // #4
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
The value you pass for the data
property should be an object, not a string: 您为
data
属性传递的值应该是一个对象,而不是字符串:
data: myData,
the property names need to match: 属性名称必须匹配:
var myData = { Prop1: '', Prop2: ''};
you need to use the [FromBody]
attribute on your parameter value: 您需要在参数值上使用
[FromBody]
属性:
public ActionResult SubmitMyData([FromBody] MyParamModel myParam)
and the properties on your model type need to be public
: 并且模型类型上的属性必须是
public
:
public class MyParamModel
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.