前言
剛開始做AJAX應(yīng)用的時(shí)候,經(jīng)常要手工解析客戶端傳遞的參數(shù),這個(gè)過程極其無聊,而且代碼中充斥著:Request["xxx"]之類的代碼。
這篇文章的目的就是告訴初學(xué)者如何自動(dòng)將客戶端用AJAX發(fā)送的參數(shù)自動(dòng)綁定為強(qiáng)類型的成員屬性或方法參數(shù)。
自動(dòng)綁定到ASPX和ASHX
框架支持
代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Happy.Web
{
public interface IWantAutoBindProperty
{
}
}
代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Happy.Web
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public sealed class AutoBind : Attribute
{
}
}
代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using Happy.ExtensionMethods.Reflection;
namespace Happy.Web
{
public class JsonBinderModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
}
private void OnPreRequestHandlerExecute(object sender, EventArgs e)
{
if (!(HttpContext.Current.CurrentHandler is IWantAutoBindProperty))
{
return;
}
var properties = HttpContext.Current.CurrentHandler.GetType().GetProperties();
foreach (var property in properties)
{
if (!property.IsDefined(typeof(AutoBind), true))
新聞熱點(diǎn)
疑難解答
圖片精選