具有动态数据类型的ASP.Net WebMethod的jQuery AJAX POST对象

时间:2015-07-10 16:43:42

标签: asp.net json http-post webmethod jquery-ajaxq

嗨,
任何人都知道我在这里做错了什么。我试着 使用jQuery AJAX将JSON对象POST到ASP.Net WebMethod。

虽然我在服务器端获取对象但不是我的方式 通缉。我希望客户对象是一个简单的对象,所以我可以像普通实例一样访问,例如customer.Name,但我不能,因为它作为字典对象到达那里。

编辑::为什么JSON作为c#动态类型的字典对象在服务器端获得?

这是快速观看屏幕播放; json object not as simple object but coming as dictionary

这是javascript和服务器端代码。

 function SaveCustomer() {
  var funcParams = JSON.stringify({
    customer: {
      Name: "Name of Customer",
      Title: "President"
    },
    address: {
      Street: "Street",
      City: "",
      Zip: ""
    }
  });

//我尝试使用以下json参数,但结果仍然相同。

var funcParams = "{\"customer\":" + JSON.stringify({ Name: "Name of
 Customer", Title: "President" }) + ",\"address\":" + 
JSON.stringify({ Street: "Street", City: "", Zip: "" }) + "}";
}

 $.ajax({ type: "POST", contentType: "application/json; charset=utf-8",
 dataType: "json", url: "aspxPage.aspx/SaveCustomer", data: funcParams,
 success: function(){  }, error: function(e){alert("Error occured"+e);} 
 })


[WebMethod(EnableSession = true)]
public static string SaveCustomer(dynamic customer, dynamic address)
{
     if(!string.IsNullOrEmpty(customer.Name) && 
         !string.IsNullOrEmpty(customer.Title)....)
      {
           //app logic
      }
}

2 个答案:

答案 0 :(得分:2)

我刚刚处理了这个场景。这是我的解决方案,如果像我一样,你没有创建DTO课程。

1)将序列化的JSON字符串传递给WebMethod

$.ajax({ type: "POST", contentType: "application/json; charset=utf-8",
 dataType: "json", url: "aspxPage.aspx/SaveCustomer", data: "{data: '" + funcParams + "'}",
 success: function(){  }, error: function(e){alert("Error occured"+e);} 
 })

2)使用JSON.NET反序列化字符串,你很高兴。

[WebMethod(EnableSession = true)]
public static string SaveCustomer(string data)
{
   dynamic customer = JsonConvert.DeserializeObject(data);
   customer.Name;
   customer.Address;
  .....
}

答案 1 :(得分:1)

我的建议是创建DTO对象以匹配该JSON,然后将您的方法参数更改为Customer和Address类型而不是动态。像这样,例如:http://encosia.com/using-complex-types-to-make-calling-services-less-complex/

您可以使用Visual Studio's "Paste JSON as Classes"来快速/轻松地创建这些课程。

如果您出于某种原因绝对无法使用专用DTO课程,请尝试使用ExpandoObject作为参数类型而不是dynamic。自从我与之合作以来已经很长时间了,我不记得他们是否在WebMethods中正确反序列化,但我认为他们做到了。请理解,与常规DTO POCO相比,动态方法会产生性能损失。