【问题标题】:Pass array to client side for display将数组传递到客户端进行显示
【发布时间】:2010-03-20 02:27:37
【问题描述】:

我有一个包含大约 50-200 个超链接的数组。如何将此数组传递给客户端,以便我可以遍历数组并将每个超链接显示为列表项? 该数组将存储在“应用程序”中,因为它是系统范围的并且很少更改。是否有更有效的方法将超链接实现为列表?

谢谢

【问题讨论】:

  • 为什么要在客户端迭代?而不是在服务器端构建列表?
  • 迭代客户端是我最初的想法,但是,你是对的,在服务器端做会更有意义。
  • 无论您创建链接服务器端还是客户端,我都没有看到它有很大的不同。取决于应用程序的设计。如果您在客户端进行传输,则传输会更小,但考虑到有效负载的大小(200 个链接),这可能无论如何都无关紧要。

标签: asp.net javascript jquery list client-side


【解决方案1】:

从 Web 表单、JSON 和 JQuery 开始的一个非常好的地方是这个链接:

http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

还可以查看 JSON.NET:http://www.codeplex.com/Json

【讨论】:

    【解决方案2】:

    虽然我知道您是从应用程序获取 URL,但此示例使用了一个人为的 url 源,您可以根据需要对其进行修改。我认为您可能想要存储 url/链接文本,所以我使用 KeyValuePair<string,string> 作为数组元素类型。如果您确实只需要 URL,只需将 KeyValuePair<string,string> 更改为字符串即可。

    jQuery .getJSON

    使用简单的 aspx 页面处理程序将完成如下操作:

    UriListHandler.aspx

    <%@ Page Language="C#" %>
    
    <%@ Import Namespace="System.Collections.Generic" %>
    <%@ Import Namespace="System.Web.Script.Serialization" %>
    
    <script runat="server">
        protected void Page_Load(object sender, EventArgs e)
        {
            string someParam = Request["someParam"] ?? "";
    
            Response.ClearContent();
            Response.ClearHeaders();
    
            // prevent cacheing
            Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetNoStore();
    
            Response.ContentType = "text/plain";
    
            // note, this is just a list, not a dictionary. Keys need not be unique
            KeyValuePair<string, string>[] uriList = new KeyValuePair<string, string>[100];
    
            for (int i = 0; i < uriList.Length; i++)
            {
                uriList[i] = new KeyValuePair<string, string>(String.Format("http://www.example.com/page{0}.htm?someParam={1}", i, someParam), String.Format("page{0}", i));
    
            }
    
            JavaScriptSerializer serializer = new JavaScriptSerializer();
    
            string json = serializer.Serialize(uriList);
    
            Response.Write(json);
        }
    
    </script>
    

    UriListClient.htm

    <!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>
        <title></title>
    
        <script src="scripts/jquery-1.4.1.js" type="text/javascript"></script>
    
        <script type="text/javascript">
            $(document).ready(function() {
    
                $('#getUriListButton').click(function() {
    
                    $.getJSON('UriListHandler.aspx',
                        { someParam: "HEY" },
                        function(responseObj, status, xhr) {
    
                            var list = $('<div/>');
                            for (var i = 0; i < responseObj.length; i++) {
                                var link = $('<a/>').attr('href', responseObj[i].Key).html(responseObj[i].Value);
                                list.append(link).append('<br/>');
                            }
                            var uriListContainer = $('#uriListContainer');
                            uriListContainer.html('').append(list);
                        });
                });
            });
        </script>
    
    </head>
    <body>
        <button id="getUriListButton">
            Get Uri List</button>
        <div id="uriListContainer">
        </div>
    </body>
    </html>
    

    jQuery.ajax

    使用网络服务将引入一些新概念,例如使用“ScriptService”属性。

    UriListService.asmx.cs

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Web;
    using System.Web.Script.Services;
    using System.Web.Services;
    
    namespace WebApplication1
    {
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [ToolboxItem(false)]
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
        [ScriptService] // we uncommented the following line ;-)
        public class UriListService : WebService
        {
            [WebMethod]
            public KeyValuePair<string, string>[] GetUriList(string someParam)
            {
                // prevent cacheing
                HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                HttpContext.Current.Response.Cache.SetNoStore();
    
                // note, this is just a list, not a dictionary. Keys need not be unique
                var uriList = new KeyValuePair<string, string>[100];
    
                for (int i = 0; i < uriList.Length; i++)
                {
                    uriList[i] =
                        new KeyValuePair<string, string>(
                            String.Format("http://www.example.com/page{0}.htm?someParam={1}", i, someParam),
                            String.Format("page{0}", i));
                }
    
                return uriList;
            }
        }
    }
    

    UriListServiceClient.htm

    <!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>
        <title></title>
    
        <script src="scripts/jquery-1.4.1.js" type="text/javascript"></script>
    
        <script type="text/javascript">
            $(document).ready(function() {
    
                $('#getUriListButton').click(function() {
                    $.ajax({
                        url: 'UriListService.asmx/GetUriList',
                        type: "post", // http post to ScriptService
                        data: '{"someParam": "HEY"}', // the params expected by the server
                        contentType: "application/json", // sending json request
                        dataType: "json", // expecting json response
                        success: function(data) {
                            var unwrappedDate = data.d;
                            var list = $('<div/>');
                            for (var i = 0; i < unwrappedDate.length; i++) {
                                var link = $('<a/>').attr('href', unwrappedDate[i].Key).html(unwrappedDate[i].Value);
                                list.append(link).append('<br/>');
                            }
                            var uriListContainer = $('#uriListContainer');
                            uriListContainer.html('').append(list);
                        },
                        error: function(a, b, c) {
    
                            alert(a.responseText);
                        }
    
                    });
                });
    
    
            });
        </script>
    
    </head>
    <body>
        <button id="getUriListButton">
            Get Uri List</button>
        <div id="uriListContainer">
        </div>
    </body>
    </html>
    

    .ASPX 代码隐藏

    在没有来自代码隐藏的 ajax 的情况下做到这一点是相当简单的

    UriListFromCodeBehind.aspx

    <%@ Page Language="C#" %>
    
    <%@ Import Namespace="System.Collections.Generic" %>
    
    <script runat="server">
    
        public static void RenderUriList(string someParam)
        {
    
    
            // note, this is just a list, not a dictionary. Keys need not be unique
            var uriList = new KeyValuePair<string, string>[100];
    
            for (int i = 0; i < uriList.Length; i++)
            {
                uriList[i] =
                    new KeyValuePair<string, string>(
                        String.Format("http://www.example.com/page{0}.htm?someParam={1}", i, someParam),
                        String.Format("page{0}", i));
            }
    
    
            for (int i = 0; i < uriList.Length; i++)
            {
                HttpContext.Current.Response.Write(String.Format("<a href='{0}'>{1}</a><br/>\r\n", uriList[i].Key, uriList[i].Value));
    
            }
    
        }
    </script>
    
    <!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">
        <div>
            Uri List:<br />
            <%
                RenderUriList("HEY"); %>
        </div>
        </form>
    </body>
    </html>
    

    希望对您有所帮助, 天空

    【讨论】:

      【解决方案3】:

      您可以将数组转换为JSON 并在客户端对其进行处理。

      【讨论】:

      • 我尝试测试将字符串作为 JSON 传递,但我无法让它工作。我创建了一个 webmethod,它返回一个字符串并将此代码放在我的 aspx 中:$.getJSON('MyPage/GetString', function(data) { alert("Working"); }); 但是,警报甚至没有显示。我究竟做错了什么?谢谢
      • 返回JSON时,可能需要将HTTP头设置为application/json
      • 我尝试添加Response.Headers.Add("contentType", "application/json");,但没有成功。我做错了吗?
      • 也许;如果您仍打算使用客户端方法,则发布更多代码会有所帮助。
      【解决方案4】:

      使用 ASPNET MVC 可以让这变得超级简单。即使您从未使用过 ASPNET MVC,您也可以轻松地在您的 ASP.NET 应用程序中使用它。

      您需要一个控制器和至少一个操作。该操作应返回 JsonResult。

      在代码中是这样的:

      using System.Collections.Generic;
      using System.Web.Mvc;
      using System.Web.Mvc.Ajax;
      
      namespace MvcApplication1.Controllers
      {
          public class DemoController : Controller // the name is used in the URL
          {
              public JsonResult LinkList(int? arg)  // the name is used in the URL
              {
                  var = new List<String>();
                  // build the list here.  You could also use an existing one. 
                  foreach (string link in linkSet)
                      list.Add(link);
                  return this.Json(list, JsonRequestBehavior.AllowGet);
              }
          }
      }
      

      将其拖放到 ASPNET 应用程序的 App_Code 子目录中。
      该方法类似于 ASMX 中的 [WebMethod],但它生成 JSON。要调用它,请在 http://server/vdir/Demo/LinkList 上执行 GET。 “Demo”部分是Controller类的名称,减去后缀“Controller”。 url 路径中的“LinkList”是控制器上方法的名称。它需要公开。

      此方法生成的 json 如下所示:

      [ "http://jvcpbdvcj/scbwkthoxlng/lhxktjght/zgfd/cuuenirukwag",
        "http://vskwkzpwaxn/eeitpup/twwshynjjcw/lblxdx/rwljaqicfgpz",
        "http://foczucekdl/ljap/napvchbkcs", 
        ....
      ]
      

      这只是一个简单的一维链接数组。使用 jQuery 从浏览器发出必要的请求非常简单。

          $.ajax({
            url     : "http://myserver/vdir/Demo/LinkList",
            type    : "GET", // http method
            cache   : false,
            success : function(result) {  // called on successful (200) reply
               ....
            }
          });
      

      在成功函数中,您可以迭代列表,将&lt;a&gt; 元素或任何您喜欢的元素发送到您的文档中。像这样:

            success : function(result) {
              if (result !== null){
                for(var i = 0; i < result.length; i++) {
                  var onelink = '<a href="' + result[i] + '">link ' + i + '</a><br/>';
                  $('#output').append(onelink);
                }
              }
            }
      

      当然,您可以添加它以使其更精细。您可以参数化 GET 请求。您可以更改传出 JSON 的形状,使其成为具有各种属性(时间戳、id、任何您喜欢的)的对象,而不仅仅是一个简单的数组。在生成链接列表时,您可以在浏览器端更加优雅。还有很多其他选择。但你明白了。


      在为浏览器客户端提供服务时,ASPNET MVC 比 ASMX 更可取,因为它内置了对 JSON 序列化的支持,而且模型超级简单。请注意,我不必显式设置内容类型,也不必手动创建 JSON,也不必在 Response 上摆弄其他东西,等等。它只是工作。

      相关:How can I implement a site with ASP.NET MVC without using Visual Studio?

      【讨论】:

      • @Cheeso,WebService 上的 ScriptService 属性使 JSON 调用对实现透明,就像您描述 MVC 控制器一样,因此只有在网站建立在 MVC 上时才使 MVC 更可取。
      【解决方案5】:

      如果你不关心搜索引擎,那就在客户端做,json 是我的首选。但是,如果您希望搜索引擎能够看到这些链接,那么服务器端是您唯一的选择。

      【讨论】:

        猜你喜欢
        • 2018-06-18
        • 2016-01-10
        • 1970-01-01
        • 2017-09-15
        • 1970-01-01
        • 2020-07-10
        • 1970-01-01
        • 2013-02-21
        • 2010-11-05
        相关资源
        最近更新 更多