Asp.net 将数组传递到客户端进行显示

Asp.net 将数组传递到客户端进行显示,asp.net,javascript,jquery,list,client-side,Asp.net,Javascript,Jquery,List,Client Side,我有一个数组,其中包含大约50-200个超链接。如何将该数组传递给客户端,以便遍历该数组并将每个超链接显示为列表项? 阵列将存储在“应用程序”中,因为它是系统范围的,很少更改。有没有一种更有效的方法来实现作为列表的超链接 谢谢,您可以将数组转换为并在客户端处理它。从Web表单和JSON开始,一个非常好的地方是以下链接: 还可以查看JSON.NET:使用ASPNET MVC可以让这一切变得非常简单。即使您从未使用过ASP.NET MVC,在ASP.NET应用程序中使用它也很容易 您将需要一个控制

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


谢谢,您可以将数组转换为并在客户端处理它。

从Web表单和JSON开始,一个非常好的地方是以下链接:


还可以查看JSON.NET:

使用ASPNET MVC可以让这一切变得非常简单。即使您从未使用过ASP.NET 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);
        }
    }
}
它只是一个简单的一维链接数组。使用jQuery从浏览器发出必要的请求非常简单

    $.ajax({
      url     : "http://myserver/vdir/Demo/LinkList",
      type    : "GET", // http method
      cache   : false,
      success : function(result) {  // called on successful (200) reply
         ....
      }
    });
在success函数中,您可以迭代列表,发出

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


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

相关的:


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

当我意识到您是从应用程序获取url时,这个示例使用了一个人为的url源,您可以根据自己的需要进行修改。我认为您可能希望存储url/链接文本,因此我使用
KeyValuePair
作为数组元素类型。如果您确实只需要URL,只需将
KeyValuePair
更改为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>
<%@ 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>

受保护的无效页面加载(对象发送方、事件参数e)
{
字符串someParam=Request[“someParam”]??“”;
Response.ClearContent();
Response.ClearHeaders();
//防止缓存
SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Response.ContentType=“text/plain”;
//注意,这只是一个列表,不是字典。键不必是唯一的
KeyValuePair[]uriList=新的KeyValuePair[100];
for(int i=0;i
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>
<!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>

$(文档).ready(函数(){
$('#getUriListButton')。单击(函数(){
$.getJSON('uristHandler.aspx',
{someParam:“嘿”},
功能(响应bj、状态、xhr){
变量列表=$('');
对于(变量i=0;i\r\n',uriList[i].Key,uriList[i].Value));
}
}
Uri列表:
希望有帮助,
Sky

我尝试将字符串作为JSON传递,但无法使其工作。我创建了一个webmethod,返回一个字符串,并将此代码放入我的aspx:
$.getJSON('MyPage/GetString',函数(数据){alert(“Working”);})
但是,警报甚至没有显示。我做错了什么?谢谢当返回JSON时,您可能需要将HTTP头设置为
application/JSON
我尝试添加
Response.Headers.Add(“contentType”,“application/JSON”)
但它不起作用。我做错了吗?也许;如果你发布更多的代码,如果你仍然计划使用客户端方法,这会有所帮助。为什么你想在客户端进行迭代?而不是在服务器端建立列表?迭代客户端是我最初的想法,但是,你是对的,这样做更有意义r端。我看不出这有多大区别,不管你是在服务器端还是客户端创建链接。这取决于应用程序的设计。如果你在客户端创建链接,传输会更小,但考虑到有效负载的大小(200个链接),这可能是无关紧要的@Cheeso,WebService上的ScriptService属性使JSON调用对实现透明,就像您描述的MVC控制器一样,因此只有当网站构建在MVC上时,MVC才更可取。
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;
        }
    }
}
<!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>
<%@ 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>