我正在尝试将Json数据从html页面发布到ASP页面并在函数中接收它。 像这样:
address1 = [["123 Main St", "", "MESA", "AZ", ""],
["5088 n desert ln", "", "PRESCOTT VALLEY", "AZ", "86314"]];
address1 = JSON.stringify(address1);
$.ajax({
url: "Default2.aspx/GetPostData",
type: "post",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: '{"address1":"' + address1 + '"}',
traditional : true,
success: function (data2) {
alert("success::" + data2.d);
},
error: function (response) {
alert("ERROR:::" + response.d);
}
});
并在asp页面中的以下函数中接收它
[System.Web.Services.WebMethod]
public static string GetPostData(String address1)
{
------
}
但是数据没有以json格式接收 它是作为文本接收的 如图所示
123 Main St ,, MESA,AZ ,, 5088 n desert ln ,, PRESCOTT VALLEY,AZ,86314
我想只收到json ..
请说明我在做什么错误。
答案 0 :(得分:0)
如果更改函数签名以使用对象,则可以使用JsonConvert将此对象转换为C#模型。我正在处理的ASP.NET应用程序中的一些示例代码:
[Route("api/inviteuser/{model}")]
[HttpPut]
public HttpResponseMessage InviteUser(Object model)
{
var jsonString = model.ToString();
InviteUserModel result = JsonConvert.DeserializeObject<InviteUserModel>(jsonString);
}
InviteUserModel是一个简单的C#对象:
public class InviteUserModel
{
public string EmailAddress { get; set; }
public string Message { get; set; }
public long CurrentCompId { get; set; }
}
答案 1 :(得分:0)
我在这里发现了两个问题:
1-在Ajax调用中,json无效。改为。还可以使您的地址元素更加标准化。
var address1 = [{&#34; Street1&#34;:&#34; 123 Main St&#34;,&#34; Street2&#34;:&#34;&#34;,&#34; City&#34;:&#34; MESA&#34;,&#34; State&#34;:&#34; AZ&#34;,&#34; Zip&#34;:&#34;&#34; }, {&#34; Street1&#34;:&#34; 5088 n desert ln&#34;,&#34; Street2&#34;:&#34;&#34;,&#34; City&#34;:& #34; PRESCOTT VALLEY&#34;,&#34; State&#34;:&#34; AZ&#34;,&#34; Zip&#34;:&#34; 86314&#34; }];
$。AJAX({
url: "http://localhost:63850/Default.aspx/GetPostData",
type: "post",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: '{"address1":' + address1 + '}',
//'{"address1":"' + address1 + '"}',
traditional: true,
success: function (data2) {
alert("success::" + data2.d);
},
error: function (response) {
alert("ERROR:::" + response.d);
}
});
2- web meothod参数是字符串,而address1作为数组传递。
Asp.NET为此抛出了这个错误。 {&#34;消息&#34;:&#34;类型\ u0027System.String \ u0027不支持反序列化数组...
创建地址容器类并将Web方法参数设置为List:
public class Address
{
public string Street1 { get; set; }
public string Street2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostCode { get; set; }
}
[System.Web.Services.WebMethod]
public static string GetPostData(List<Address> addresses)
{
// addresses[0].Street1;
// addresses[0].City;
return null;
}
3-如果您不想更改地址javascript数组。
[System.Web.Services.WebMethod]
public static string GetPostData(object address1)
{
List<string[]> list = new List<string[]>();
string[][] addresses = new string[2][];
foreach (var addressList in address1 as object[])
{
string[] addressElement = new string[5];
int index = 0;
foreach (var temp in addressList as object[])
{
addressElement[index++] = (temp != null) ? temp.ToString() : string.Empty;
}
list.Add(addressElement);
}
return null;
}