使用jQuery成功将JSON对象发送到ASP.NET WebMethod

使用jQuery成功将JSON对象发送到ASP.NET WebMethod,第1张

使用jQuery成功将JSON对象发送到ASP.NET WebMethod

使用AJAX.NET时,我总是使输入参数只是一个普通的旧对象,然后使用javascript反序列化器将其转换为所需的任何类型。至少以这种方式,您可以调试并查看Web方法正在接收的对象类型。

使用jQuery时需要将对象转换为字符串

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title></title></head><body>    <form id="form1" runat="server">        <asp:scriptManager ID="sm" runat="server" EnablePageMethods="true"> <scripts>     <asp:scriptReference Path="~/js/jquery.js" /> </scripts>        </asp:scriptManager>        <div></div>    </form></body></html><script type="text/javascript" language="javascript">    var items = [{ compId: "1", formId: "531" },        { compId: "2", formId: "77" },        { compId: "3", formId: "99" },        { status: "2", statusId: "8" },        { name: "Value", value: "myValue"}];        //Using Ajax.Net Method        PageMethods.SubmitItems(items, function(response) { var results = response.d; }, function(msg) { alert(msg.d) }, null);        //using jQuery ajax Method        var options = { error: function(msg) { alert(msg.d); },  type: "POST", url: "WebForm1.aspx/SubmitItems",  data: {"items":items.toString()}, // array to string fixes it *  contentType: "application/json; charset=utf-8",  dataType: "json",  async: false,   success: function(response) { var results = response.d; } };         jQuery.ajax(options);</script>

和背后的代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services;using System.Web.script.Serialization;using System.Web.script.Services;using System.Web.UI;using System.Web.UI.WebControls;namespace CustomEquip{    [scriptService]    public partial class WebForm1 : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {        }        [WebMethod]        public static void SubmitItems(object items)        { //break point here List<object> lstItems = new JavascriptSerializer().ConvertToType<List<object>>(items);        }    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5477365.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存