I want to return List<ClassName> & count(int) from code-behind(C#) to javascript. How can i do this?
-
List of any class e.g EmpDetailsUlhas Tuscano– Ulhas Tuscano2011-04-01 07:23:22 +00:00Commented Apr 1, 2011 at 7:23
-
More information about your specific situation would be helpful, but as general advice you could do an AJAX POST to a web service that returns yor data in JSON form.Sapph– Sapph2011-04-01 07:28:44 +00:00Commented Apr 1, 2011 at 7:28
-
I've updated my answer with some code. Hope it helps.LeftyX– LeftyX2011-04-01 07:46:28 +00:00Commented Apr 1, 2011 at 7:46
Add a comment
|
2 Answers
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" %>
Comments
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