webform 中使用ajax

常用的方式有 js –> WebService  , js->*.ashx, js->WebAPI, js->MVC Controller->Action. 前两种就不说了.

一、Webform中 js-> WebAPI .

1.在需要的地方,直接添加WebAPI

webform 中使用ajax

2.在Global.asax中设置一下.

public class Global : System.Web.HttpApplication
{ void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.IgnoreRoute("{resource}.aspx/{*pathInfo}"); //api
var route = RouteTable.Routes.MapHttpRoute(name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });
route.RouteHandler = new SessionStateHttpControllerRouteHandler();

3.改一下WebAPI,需要理解FormBody,FromUri的区别.返回Json还是xml格式,是根据请求时的ContentType决定的.

public class UserController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
} // GET api/<controller>/5
[HttpGet()]
//[ActionName("getValue")]
public string GetById([FromBody]dynamic obj)
{
var session = HttpContext.Current.Session;
var user = HttpContext.Current.User;
return "value" + "aabbccdd";
} // POST api/<controller>
[HttpPost]
public object Test(dynamic value)
{
var x = value["A"];
return x;
}

4,js调用 WebAPI方法,注意发送数据的格式.是字符串,不是Json.

function test() {
var options = {};
options.url = "/api/user/Test";
options.type = "post";
options.data =

JSON.stringify

({ 'A': 1, 'B': 2 });
options.contentType = "application/json";
options.success = function (customer) {
alert(customer);
};
options.error = function (err) { alert(err.statusText); };
$.ajax(options);
}; function submitForm() {
var s = $("#from1").serializeArray();
alert(s);
var options = {};
options.url = "/api/user/submit";
options.type = "post";
options.contentType = "application/json";
options.data = JSON.stringify(s);
options.success = function (customer) {
alert(customer);
};
options.error = function (err) { alert(err.statusText); };
$.ajax(options);
}

二,webform 中 js-> asp.net mvc

1,在webform中添加 asp.net mvc相关的程序集引用.建议直接从asp.net mvc项目拷贝引用.

webform 中使用ajax

2,在web.config中需要设置作这些设置.

<compilation debug="true" targetFramework="4.0" >
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</assemblies>
</compilation>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>

3,在webform程序中,添加一个controller

webform 中使用ajax

4,在Global.asax.cs中添加mvc路由

public class Global : System.Web.HttpApplication
{ void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.IgnoreRoute("{resource}.aspx/{*pathInfo}"); //mvc
RouteTable.Routes.MapRoute(
name: "Default",
url: "mvc/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

5,在controller中添几个测试方法,同样需要注意js调用时的数据格式,默认只接收post调用.get请求时.需设置JsonRequestBehavior.AllowGet

public class HomeController : Controller
{
public JsonResult Index()
{
ViewBag.Message = "修改此模板以快速启动你的 ASP.NET MVC 应用程序。"; return Json(,JsonRequestBehavior.AllowGet);
} public JsonResult About()
{
ViewBag.Message = "你的应用程序说明页。";
return Json("aaa");
} public ActionResult Contact(int age,string name)
{
ViewBag.Message = "你的联系方式页。";
return Json("bbbbbbbbbbbbb");
}

6,添加测试js

function mvcpost() {
var options = {};
options.url = "/mvc/home/Contact";
options.type = "post";
options.data = JSON.stringify({ 'age': 1, 'name': 'xiaowy' });
options.contentType = "application/json";
options.success = function (customer) {
alert(customer);
};
options.error = function (err) { alert(err.statusText); };
$.ajax(options);
}

在上面的代码中,用到了一个自定义的类 SessionStateHttpControllerHandler. 这个是为了在Web API中使用 session.

public class SessionStateHttpControllerHandler : HttpControllerHandler, IRequiresSessionState
{
public SessionStateHttpControllerHandler(RouteData routeData)
: base(routeData)
{ }
} public class SessionStateHttpControllerRouteHandler : HttpControllerRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new SessionStateHttpControllerHandler(requestContext.RouteData);
}
}

如果你照上面的步骤仍然不成功,那就下载这个,自己修改一下.

上一篇:golang学习之旅:搭建go语言开发环境


下一篇:基于Redis缓存的Session共享(附源码)