简体   繁体   English

将数组传递给客户端进行显示

[英]Pass array to client side for display

I have an array which contains around 50-200 hyperlinks. 我有一个包含大约50-200个超链接的数组。 How can I pass this array to the client-side so that I can iterate through the array and display each hyperlinks as a list item? 如何将该数组传递给客户端,以便可以遍历该数组并将每个超链接显示为列表项? The array will be stored in 'Application' as it's system wide and rarely changes. 数组将存储在“应用程序”中,因为它是系统范围的文件,很少更改。 Could there be a more efficient way of achieving the hyperlinks as a list? 有没有更有效的方式可以将超链接作为列表实现?

Thanks 谢谢

A really good place to start with Web Forms and JSON and JQuery is this link: 从Web窗体,JSON和JQuery开始的一个非常好的地方是以下链接:

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

Also check out JSON.NET: http://www.codeplex.com/Json 还检查了JSON.NET: http://www.codeplex.com/Json

While I realize you are getting your URLs from Application, this example uses a contrived url source that you can modify to your needs. 当我意识到您正在从Application获取URL时,此示例使用了可修改的url源,您可以根据需要进行修改。 I would think you would probably want to store url/link text so I used KeyValuePair<string,string> as the array element type. 我认为您可能想存储url /链接文本,所以我使用KeyValuePair<string,string>作为数组元素类型。 If you truly need only the URL, simply change KeyValuePair<string,string> to string. 如果您真正只需要URL,只需将KeyValuePair<string,string>更改为string。

jQuery .getJSON jQuery .getJSON

Using a simple aspx page handler would be accomplished something like this: 使用一个简单的aspx页面处理程序将完成以下操作:

UriListHandler.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 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 jQuery.ajax

Using a webservice is going to introduce some new concepts such as using 'ScriptService' attribute. 使用Web服务将引入一些新概念,例如使用'ScriptService'属性。

UriListService.asmx.cs 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 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 codebehind .ASPX代码隐藏

To do this without ajax from codebehind is fairly trivial 在没有来自代码隐藏的ajax的情况下做到这一点相当简单

UriListFromCodeBehind.aspx 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>

Hope that helps, Sky 希望有帮助,天空

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

Using ASPNET MVC can make this super easy. 使用ASPNET MVC可以使超级简单。 Even if you've never used ASPNET MVC, it will be easy for you to employ it in your ASP.NET app. 即使您从未使用过ASPNET MVC,也很容易在ASP.NET应用程序中使用它。

You'll need a Controller, and at least one Action. 您将需要一个Controller和至少一个Action。 The action should return a JsonResult. 该操作应返回JsonResult。

it looks like this in code: 在代码中看起来像这样:

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);
        }
    }
}

Drop that into the App_Code sub-directory of the ASPNET app. 将其拖放到ASPNET应用程序的App_Code子目录中。
That method is like a [WebMethod] in ASMX, but it generates JSON. 该方法类似于ASMX中的[WebMethod],但它会生成JSON。 To invoke it, do a GET on http://server/vdir/Demo/LinkList . 要调用它,请在http://server/vdir/Demo/LinkList上执行GET。 The "Demo" part is the name of the Controller class, less the suffix "Controller". “演示”部分是Controller类的名称,但不包括后缀“ Controller”。 The "LinkList" in the url path is the name of the method on the controller. URL路径中的“ LinkList”是控制器上方法的名称。 It needs to be public. 它必须是公开的。

The json this method generates will look like this: 此方法生成的json如下所示:

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

It's just a simple 1-D array of links. 这只是一个简单的一维链接数组。 To make the necessary request from the browser is very simple using jQuery. 使用jQuery从浏览器发出必要的请求非常简单。

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

In the success function, you can iterate on the list, emitting <a> elements or whatever you like into your document. 在成功函数中,您可以在列表上进行迭代,将<a>元素或任何您喜欢的元素发送到文档中。 Like this: 像这样:

      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);
          }
        }
      }

Of course, you can add to that to make it more elaborate. 当然,您可以对其进行补充以使其更加精致。 You can parameterize the GET request. 您可以参数化GET请求。 You could change the shape of the outgoing JSON so that it's an object with various properties (timestamp, id, whatever you like), and not just a simple array. 您可以更改传出JSON的形状,以便它是一个具有各种属性(时间戳,id等)的对象,而不仅仅是一个简单的数组。 You can be more elegant on the browser side when producing the list of links. 生成链接列表时,您可以在浏览器端更加优雅。 There are lots of other options. 还有很多其他选择。 But you get the idea. 但是你明白了。


ASPNET MVC is much preferable to ASMX when servicing browser clients, because of its built-in support for JSON serialization, and because of the super simple model. 在为浏览器客户端提供服务时,ASPNET MVC比ASMX更可取,因为它内置了对JSON序列化的支持,并且具有超级简单的模型。 Notice I did not have to set the content type explicitly, or create JSON manually, or fiddle with other stuff on the Response, and so on. 请注意,我不必显式设置内容类型,也不必手动创建JSON,也不必摆弄Response上的其他内容,等等。 It just works. 它只是工作。

Related: How can I implement a site with ASP.NET MVC without using Visual Studio? 相关: 如何在不使用Visual Studio的情况下使用ASP.NET MVC实现网站?

If you don't care about search engines then do it client side, json is my preference for this. 如果您不关心搜索引擎,那么请在客户端进行操作,json是我的首选。 But if you want search engines to be able to see those links then server side is your only option. 但是,如果您希望搜索引擎能够看到这些链接,那么服务器端是您唯一的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM