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

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

嗨,
任何人都知道我在这里做错了什么。我试图 使用 jQuery AJAX 将 JSON 对象发布到 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
      }
}

最佳答案

我最近刚刚处理过这种情况。如果您像我一样决定不创建 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;
  .....
}

关于asp.net - 具有动态数据类型的 jQuery AJAX POST 对象到 ASP.Net WebMethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31346131/

相关文章:

ios - (POST 请求)从 Objective-C 中的 URL 响应解析 JSON 元素

javascript - 带有 JSON "undefined is not a function"的 jQuery cookie

android - ByteArrayOutputStream 到 FileBody

ios - 如何调用连接:didReceiveData

c# - 链接按钮的单击功能未被调用

c# - MVC 中的倒数计时器

ajax - 'JSON' 仅在 IE 中是未定义的错误

asp.net - ASP.NET MVC 中文件上的 HttpHandler

c# - ASP.NET MVC下无法使用C#设置和获取cookie

android - Android 中的 HttpPost - 无法识别的字符