简体   繁体   中英

How to send Json Data from Aspx page

I tried to use TokenInput Jquery for multiple value autocomplete where it requires the JSON response as input data

http://loopj.com/jquery-tokeninput/

I am using ASPX page as source

<script type="text/javascript" >
    $(document).ready(function() {

    $("#txtTest").tokenInput("Complete.aspx", {
        theme: "facebook"
    });

    });


</script>

Edited From Here Question: How to provide the JSON data from a aspx page in the desired format as i have datatable with values according to Querystring from Complete.aspx

 protected void Page_Load(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(Request.QueryString["q"]))
    {
        string json = "[{\"Id\":\"1\",\"name\": \"Test 1\"},{\"Id\":\"2\",\"name\": \"Test 2\"}]";
        Response.Clear(); 
        Response.ContentType = "application/json; charset=utf-8"; 
        Response.Write(json); 
        Response.End();              

    }
}  

Any help will be appreciated.

You should take a look at WCF. WCF has native support for returning JSON and you don't have to worry about string concatenation or HTTP content types.

Alternative to the WCF , you can create WebMethod in .aspx.

   [WebMethod]
    public static string Info()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        string result = js.Serialize(new string[] { "one", "two", "three" });
        return result;
    }

and request this WebMethod via Ajax call.

<script type="text/javascript">
        $(function () {
            $("#button1").click(function () {
                $.ajax({
                    url: "Default.aspx/Info",
                    data: "{}",
                    contentType: "application/json",
                    success: function (data) {
                        alert(data.d);
                    },
                    type: "post",
                    dataType : "json"
                });
            });
        });
</script>

EDIT:

Code-behind - Page_Load handler (JsonPage.aspx)

  string json = "[{\"name\":\"Pratik\"},{\"name\": \"Parth\"}]";
  Response.Clear();
  Response.ContentType = "application/json; charset=utf-8";
  Response.Write(json);
  Response.End();

and request the JsonPage.aspx via TokenInput jQuery . (Sample.aspx & JsonPage.aspx are in same folder)

<script type="text/javascript">
        $(function () {
            $("#txt1").tokenInput("JsonPage.aspx");
        });
</script>

<body>
 <input type="text" id="txt1"/>
</body>

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