How do I server AJAX calls using JSON with Web Forms?

六月ゝ 毕业季﹏ 提交于 2019-12-04 06:51:46
VladV

You could use built-in ASP.NET AJAX.

Option 1 - use a web service (if you want the functionality to be reusable):

  • create a web service (.asmx) with [ScriptService] attribute,
  • add a to your page and add the web service to its Services collection,
  • use JavaScript proxy generated by ScriptManager in yor page.

Option 2 - use page methods (if you want the functionality on a single page without creating a web service):

  • define static methods in your page, add [WebMethod] attribute to them,
  • add a ScriptManager with EnablePageMethods="true",
  • use PageMethods object to call these method from JavaScript.

In either case JSON will be used for data transfer.

Here is an extensive tutorial with some code samples.

However, ASP.NET AJAX is often blamed for inefficiency - for instance, JS it generates tends to be rather large. So, if you are concerned with performance, you'd want to test it thoroughly.

You might also have a look at this thread: .NET AJAX Calls to ASMX or ASPX or ASHX?

Use generic web handler. i.e. ashx. These are even faster than MVC actions.

If you've got .NET 3.5 installed on the server, you can take advantage of the JSON serialization tools that ship with the framework.

This uses the DataContractJsonserializer class.

My preferred method in this scenario is using a generic web handler (.ashx) and JSON.net http://james.newtonking.com/json

It's simple, fast and lightweight.

A simple example would be:

public void ProcessRequest(HttpContext context)
{
        string jsonOutput = string.Empty;
        context.Response.ContentType = "application/json";
        using (var db = new MyDBContext())
        {
            var dbResult = db.myobject.select();
            jsonOutput = Newtonsoft.Json.JsonConvert.SerializeObject(dbResult);
        }
        context.Response.Write(jsonOutput); 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!