简体   繁体   中英

How can i return List & Integer from C# to Javascript

I want to return List<ClassName> & count(int) from code-behind(C#) to javascript. How can i do this?

You can use JavaScriptSerializer:

var myClass = new ClassName();

... 

var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(myClass);

Response.Write(OutPut);

You have to import this namespace: System.Web.Script.Serialization

UPDATE:

You can use jQuery to post the request:

<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            type: 'POST',
            url: 'WebForm2.aspx',
            data: {},
            dataType: 'json',
            complete: function(XMLHttpRequest, textStatus) {
                var Response = $.parseJSON(XMLHttpRequest.responseText);
                alert(Response.Classes[0].Name);
            }
        });
    });
</script>

and this is the code-behind:

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

        var classWrapper = new ClassWrapper();

        classWrapper.Classes.Add(new ClassName() { Name = "Test 1" });
        classWrapper.Classes.Add(new ClassName() { Name = "Test 2" });
        classWrapper.Classes.Add(new ClassName() { Name = "Test 3" });
        classWrapper.Count = classWrapper.Classes.Count;


        var jSon = new JavaScriptSerializer();
        var OutPut = jSon.Serialize(classWrapper);

        Response.Write(OutPut);
    }
}

public class ClassWrapper
{
    public ClassWrapper()
    {
        Classes = new List<ClassName>();
    }
    public List<ClassName> Classes { get; set; }
    public int Count { get; set; }
}

public class ClassName
{
    public string Name { get; set; }
}

Few tricks for ASP.NET (in MVC would be easier).

in the HTML of WebForm2.aspx remove all the HTML but leave page directive:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="AutocompleteASPNET.WebForm2" %>

The best way to achieved the required functionality is to use Ajax.

For this create a page method in code behind and call that method in client side through javascript.

For more details how to call server side method from jquery,checkout the following link

Using jQuery to directly call ASP.NET AJAX page methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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