我在网上找遍了,我想我使用JSON是正确的,但我就是找不到它有什么问题。我需要将此json对象作为MVC控制器操作的参数进行传递:
JSON:
{
"ContactId": "0",
"Fax2": "dsad",
"Phone2": "dsad",
"Tittle": "asdsa",
"Cellphone": "dsadsd",
"Address": { "City": "kjshksdfks",
"Country": "undefined",
"Id": "0",
"State": "dsadsa"}
}.NET对象如下所示:
public class Contact
{
public string ContactId {get; set;}
public string Fax2 {get; set;}
public string Phone2 {get; set;}
public string Tittle {get; set;}
public string Cellphone {get; set;}
public Address ContactAddress {get; set;}
}嵌套地址类型如下:
public class Address
{
public string City {get; set;}
public string Country {get; set;}
public int Id {get; set;}
public string State {get; set;}
}我的JSON有什么问题?为了将干净的东西传递给控制器操作,我遗漏了什么?
确切的错误是:无效的JSON原语:联系人
注意:我尝试使用javascript对象、JSON.stringify和toJSON()
提前感谢!
发布于 2012-05-14 23:45:36
完成后,我将分享解决方案:
由于提交的是类型为" json“的请求,因此附加类型必须位于json中,否则路由引擎会将其视为非json对象,并因此标记为json无效,因此,在我的示例中,我这样做:
{
"ContactId": "a",
"Fax2": "b",
"Phone2": "c",
"Title": "d",
"Cellphone": "e",
"ContactAddress": {
"Id": 22,
"City": "a",
"State": "b",
"Country": "c"
}
},{"provider": 1}虽然不需要任何额外的配置来传递额外的参数,因为我们使用的是JSON,但在使用.NET对象的不同场景中,我们必须指定控制器可以接受许多参数。因此,要做到这一点,我们必须配置控制器路由:
context.MapRoute(
"Providers_default",
"Catalogs/{controller}/{action}/{id1}/{id2}",
new { controlller = "Provider", action = "Index", id = UrlParameter.Optional }
);这里有一个链接:http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx
诚挚的问候!
发布于 2012-05-14 15:55:08
我怀疑您缺少ajax调用的内容类型。另请参阅:http://forums.asp.net/t/1665485.aspx/1?asp+net+mvc+3+json+values+not+recieving+at+controller。
我已经更改了几个东西1)小->标题,和地址-> ContactAddress;这应该可以工作:
JSON:
{
"ContactId": "a",
"Fax2": "b",
"Phone2": "c",
"Title": "d",
"Cellphone": "e",
"ContactAddress": {
"Id": 22,
"City": "a",
"State": "b",
"Country": "c"
}
}呼叫:
<script>
var contact = { "ContactId": "a", "Fax2": "b", "Phone2": "c", "Title": "d", "Cellphone": "e", "ContactAddress": { "Id": 22, "City": "a", "State": "b", "Country": "c"} };
$.ajax({
type: 'POST',
url: '[YOUR-URL]',
data: JSON.stringify(contact),
success: function (result) {
alert('success');
},
dataType: "json",
contentType: "application/json; charset=utf-8"
});
</script>https://stackoverflow.com/questions/10577103
复制相似问题