Passing an array to the client side for display

I have an array containing about 50-200 hyperlinks. How to pass this array to the client side so that I can iterate through the array and display each hyperlink as a list item? The array will be stored in the "application" as its system scale and rarely changes. Could there be a more efficient way to achieve list hyperlinks?

thank

+3
source share
5 answers

A good place to get started with Web Forms and JSON and JQuery is this link:

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

JSON.NET: http://www.codeplex.com/Json

+4

, URL- , url, . , , , url/link, 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 codebehind

ajax codebehind

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>

, , Sky

+2
+1

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

App_Code ASPNET.
[WebMethod] ASMX, JSON. , GET http://server/vdir/Demo/LinkList. "" - Controller, "". "LinkList" URL- - . .

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

, <a> , . :

      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, (timestamp, id, , ), . . . .


ASPNET MVC ASMX - JSON - . , , JSON , , . .

: ASP.NET MVC Visual Studio?

0
source

If you don’t like search engines, do it on the client side, json is my preference. But if you want search engines to be able to see these links, the server side is your only option.

0
source

Source: https://habr.com/ru/post/1737772/


All Articles