前言
剛開始做AJAX應用的時候,經常要手工解析客戶端傳遞的參數,這個過程極其無聊,而且代碼中充斥着:Request["xxx"]之類的代碼。
這篇文章的目的就是告訴初學者如何自動將客戶端用AJAX發送的參數自動綁定為強類型的成員屬性或方法參數。
自動綁定到ASPX和ASHX
框架支持
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Happy.Web 8 { 9 public interface IWantAutoBindProperty 10 { 11 } 12 }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Happy.Web 8 { 9 [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] 10 public sealed class AutoBind : Attribute 11 { 12 } 13 }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 using System.Web; 8 9 using Newtonsoft.Json; 10 11 using Happy.ExtensionMethods.Reflection; 12 13 namespace Happy.Web 14 { 15 public class JsonBinderModule : IHttpModule 16 { 17 public void Init(HttpApplication context) 18 { 19 context.PreRequestHandlerExecute += OnPreRequestHandlerExecute; 20 } 21 22 private void OnPreRequestHandlerExecute(object sender, EventArgs e) 23 { 24 if (!(HttpContext.Current.CurrentHandler is IWantAutoBindProperty)) 25 { 26 return; 27 } 28 29 var properties = HttpContext.Current.CurrentHandler.GetType().GetProperties(); 30 31 foreach (var property in properties) 32 { 33 if (!property.IsDefined(typeof(AutoBind), true)) 34 { 35 continue; 36 } 37 38 string json = HttpContext.Current.Request[property.Name]; 39 40 var value = JsonConvert.DeserializeObject(json, property.PropertyType); 41 42 property.SetValue(HttpContext.Current.Handler, value); 43 } 44 } 45 46 public void Dispose() 47 { 48 } 49 } 50 }
代碼示例
1 <?xml version="1.0" encoding="utf-8"?> 2 3 <configuration> 4 5 <system.web> 6 <compilation debug="false" targetFramework="4.0" /> 7 <httpModules> 8 <add name="JsonBinderModule" type="Happy.Web.JsonBinderModule"/> 9 </httpModules> 10 </system.web> 11 12 </configuration>
1 /// <reference path="../ext-all-debug-w-comments.js" /> 2 var data = { 3 Name: '段光偉', 4 Age: 28 5 }; 6 7 Ext.Ajax.request({ 8 url: '../handlers/JsonBinderTest.ashx', 9 method: 'POST', 10 params: { user: Ext.encode(data) } 11 });
1 <%@ WebHandler Language="C#" Class="JsonBinderTest" %> 2 3 using System; 4 using System.Web; 5 6 using Happy.Web; 7 8 public class JsonBinderTest : IHttpHandler, IWantAutoBindProperty 9 { 10 [AutoBind] 11 public User user { get; set; } 12 13 public void ProcessRequest(HttpContext context) 14 { 15 context.Response.ContentType = "text/plain"; 16 context.Response.Write(string.Format("姓名:{0},年齡:{1}", user.Name, user.Age)); 17 } 18 19 public bool IsReusable 20 { 21 get 22 { 23 return false; 24 } 25 } 26 } 27 28 public class User 29 { 30 public string Name { get; set; } 31 32 public int Age { get; set; } 33 }
運行結果

自動綁定到MVC
框架支持
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 using System.Web.Mvc; 8 9 using Newtonsoft.Json; 10 11 namespace Tenoner.Web.Mvc 12 { 13 public class JsonBinder : IModelBinder 14 { 15 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 16 { 17 string json = controllerContext.HttpContext.Request[bindingContext.ModelName]; 18 19 return JsonConvert.DeserializeObject(json, bindingContext.ModelType); 20 } 21 } 22 }
代碼示例
此處省略代碼示例,有興趣的朋友請留言交流。
備注
有些朋友應該能想到,這種模式不止能用在AJAX場景,其它場景也可以使用。
