开发者

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 ca开发者_如何学Cn 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜