How to send Json Data from Aspx page

爷,独闯天下 提交于 2019-12-10 10:46:52

问题


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.


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/11613194/how-to-send-json-data-from-aspx-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!