How to send Json Data from Aspx page

心不动则不痛 提交于 2019-12-06 06:02:00

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>

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.

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