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

时光总嘲笑我的痴心妄想 提交于 2019-12-21 12:25:01

问题


I know MVC controllers are quite good at serving JSON formatted AJAX requests, but is there any built-in ASP.NET functionality I can use for these type calls from a plain old web forms site?


回答1:


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?




回答2:


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




回答3:


Web API works fine with Web Forms. http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-aspnet-web-forms




回答4:


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.




回答5:


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); 
}


来源:https://stackoverflow.com/questions/2361380/how-do-i-server-ajax-calls-using-json-with-web-forms

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