【问题标题】:Understanding Difference between ToArray and JSON了解 ToArray 和 JSON 之间的区别
【发布时间】:2011-11-12 05:58:08
【问题描述】:

我正在使用 jquery 将数据绑定到下拉列表,并且我还使用了 Web 服务方法,它工作得很好,但我没有得到一些澄清,例如将数据绑定到我得到的一个下拉列表来自返回到数组对象的 web 方法的数据,对于另一个下拉列表,我从 web 方法获取数据,该方法以 JSON 对象的形式返回,但在前端我没有得到任何区别。他们中的大多数人都在告诉序列化 json 的好方法,那么这里到底发生了什么?我有点困惑 请帮我 谢谢

**here is my code**
Default.aspx

<html>
<head runat="server">
    <title>JsonAndToArray</title>

    <script type="text/javascript" src="js/jquery.min.js"></script>

    <script type="text/javascript">

        $(document).ready(function() {
            ddlActivityType = document.getElementById("<%=ddlActivity.ClientID %>");
            $.ajax({
                type: "POST",
                contentType: "application/json;charset/utf-8",
                url: "Visit.asmx/GetActivityByJSON",
                dataType: "json",
                success: function(results) {
                    results = eval(results.d);
                    $('#ddlActivity').get(0).options.length = 0;
                    $('#ddlActivity').get(0).options[0] = new Option('  --select--  ', '0');
                    $.each(results, function(val, text) {
                        $('#ddlActivity').append($('<option></option>').val(text[1]).html(text[0]));
                    });
                }
            });

            ddlActivityType1 = document.getElementById("<%=ddlActivity2.ClientID %>");
            $.ajax({
                type: "POST",
                contentType: "application/json;charset/utf-8",
                url: "Visit.asmx/GetActivity",
                dataType: "json",
                success: function(results) {
                    results = eval(results.d);
                    $('#ddlActivity2').get(0).options.length = 0;
                    $('#ddlActivity2').get(0).options[0] = new Option('--select--', '0');
                    $.each(results, function(val, text) {
                        $('#ddlActivity2').append($('<option></option>').val(text[1]).html(text[0]));
                    });
                }
            });
        });

    </script>

</head>
<body>
    <form id="form1" runat="server">
    Json-Activity :
    <select id="ddlActivity" runat="server">
    </select>   
    <br />
    <br />
    ToArray-Activity :
    <select id="ddlActivity2" runat="server">
    </select>
    <br />
    <br />
    <asp:Button ID="btnJson" runat="server" Text="Json" OnClick="Json_click"/>
    </form>
</body>
</html>


Defalut.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;

public partial class Defalut: System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Json_click(object sender,EventArgs e)
    {
    }
}


**webservices**

**

 - Visit.asmx

**


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using Facade;

/// <summary>
/// Summary description for Visit
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class Visit : System.Web.Services.WebService
{

    public Visit()
    {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    [WebMethod]
    public IList<string[]> GetActivity()
    {
        IList<string[]> values = new List<string[]>();
        //string value = "";
        try
        {
            SqlConnection con_New = new SqlConnection(@"Data Source=SQLEXPRESS;Initial Catalog="Database";Integrated Security=True;");
            con_New.Open();
            SqlCommand cmdSelect_ST = new SqlCommand("select id,name from table", con_New);
            SqlDataAdapter da_ST = new SqlDataAdapter(cmdSelect_ST);

            DataSet ds = new DataSet();
            da_ST.Fill(ds);
            DataTable dt = ds.Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string[] ActivityType = new string[2];
                ActivityType[0] = dt.Rows[i]["name"].ToString();
                ActivityType[1] = dt.Rows[i]["id"].ToString();
                values.Add(ActivityType);
            }          
        }
        catch (Exception ex)
        {

        }
        return values;
    }


    [WebMethod]
    public string GetActivityByJSON()
    {
        IList<string[]> values = new List<string[]>();
        string value = "";
        try
        {
            SqlConnection con_New = new SqlConnection(@"Data Source=SQLEXPRESS;Initial Catalog="Database";Integrated Security=True;");
            con_New.Open();
            SqlCommand cmdSelect_ST = new SqlCommand("select name,id from table", con_New);
            SqlDataAdapter da_ST = new SqlDataAdapter(cmdSelect_ST);

            DataSet ds = new DataSet();
            da_ST.Fill(ds);
            DataTable dt = ds.Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string[] ActivityType = new string[2];
                ActivityType[0] = dt.Rows[i]["name"].ToString();
                ActivityType[1] = dt.Rows[i]["id"].ToString();
                values.Add(ActivityType);
            }
            JavaScriptSerializer js = new JavaScriptSerializer();
            value = js.Serialize(values);
        }
        catch (Exception ex)
        {

        }
        return value;
    }
}

【问题讨论】:

    标签: c# jquery web-services asp.net-4.0


    【解决方案1】:

    在第一次调用中,您将返回一个数组,该数组由系统转换为 json 数组。你返回这个:

    IList<string[]> values = new List<string[]>();
    

    在第二次调用中,您转换为 jsaon 数组并将其作为字符串返回。这是进行转换的代码:

    JavaScriptSerializer js = new JavaScriptSerializer();
    value = js.Serialize(values);
    

    由于 json 只是以某种方式格式化的字符串——没有区别。就在创建要发回的字符串以及谁(您的代码或系统代码)创建它时。

    【讨论】:

    • 那么没有必要进行 json 序列化并发送回前端,我们可以使用 To Array 代替它,我理解的方式正确吗?
    • 嗯...有点。系统将为您进行 json 序列化。 ToArray() 不能代替任何东西。
    • encosia.com/asmx-and-json-common-mistakes-and-misconceptions,我浏览了这篇文章,我清除了所有的钱,谢谢
    猜你喜欢
    • 2016-09-05
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2019-10-30
    • 2011-10-26
    • 2011-05-16
    • 2015-04-08
    • 2020-03-22
    相关资源
    最近更新 更多