基于.NET中:自動(dòng)將請(qǐng)求參數(shù)綁定到ASPX、ASHX和MVC的方法(菜鳥(niǎo)必看)
前言
剛開(kāi)始做AJAX應(yīng)用的時(shí)候,經(jīng)常要手工解析客戶(hù)端傳遞的參數(shù),這個(gè)過(guò)程極其無(wú)聊,而且代碼中充斥著:Request["xxx"]之類(lèi)的代碼。
這篇文章的目的就是告訴初學(xué)者如何自動(dòng)將客戶(hù)端用AJAX發(fā)送的參數(shù)自動(dòng)綁定為強(qiáng)類(lèi)型的成員屬性或方法參數(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))
{
continue;
}
string json = HttpContext.Current.Request[property.Name];
var value = JsonConvert.DeserializeObject(json, property.PropertyType);
property.SetValue(HttpContext.Current.Handler, value);
}
}
public void Dispose()
{
}
}
}
代碼示例
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="false" targetFramework="4.0" />
<httpModules>
<add name="JsonBinderModule" type="Happy.Web.JsonBinderModule"/>
</httpModules>
</system.web>
</configuration>
/// <reference path="../ext-all-debug-w-comments.js" />
var data = {
Name: '段光偉',
Age: 28
};
Ext.Ajax.request({
url: '../handlers/JsonBinderTest.ashx',
method: 'POST',
params: { user: Ext.encode(data) }
});
<%@ WebHandler Language="C#" Class="JsonBinderTest" %>
using System;
using System.Web;
using Happy.Web;
public class JsonBinderTest : IHttpHandler, IWantAutoBindProperty
{
[AutoBind]
public User user { get; set; }
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write(string.Format("姓名:{0},年齡:{1}", user.Name, user.Age));
}
public bool IsReusable
{
get
{
return false;
}
}
}
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
運(yùn)行結(jié)果
自動(dòng)綁定到MVC
框架支持
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Newtonsoft.Json;
namespace Tenoner.Web.Mvc
{
public class JsonBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
string json = controllerContext.HttpContext.Request[bindingContext.ModelName];
return JsonConvert.DeserializeObject(json, bindingContext.ModelType);
}
}
}
相關(guān)文章
Entity Framework使用Code First模式管理視圖
本文詳細(xì)講解了Entity Framework使用Code First模式管理視圖的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-03-03asp.net 類(lèi)庫(kù)中使用ConfigurationManager.ConnectionStrings
類(lèi)庫(kù)中使用ConfigurationManager.ConnectionStrings的步驟。2009-06-06AntDesign Pro + .NET Core 實(shí)現(xiàn)基于JWT的登錄認(rèn)證功能
這篇文章主要介紹了AntDesign Pro + .NET Core 實(shí)現(xiàn)基于JWT的登錄認(rèn)證功能,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03gridview行索引獲取方法及實(shí)現(xiàn)代碼
GridView行索引的獲取有利于對(duì)GridView行數(shù)據(jù)進(jìn)行操作(刪、改)等等,接下來(lái)介紹獲取方法,感興趣的朋友可以了解下,閱讀本文希望對(duì)你有幫助2013-01-01MVC4制作網(wǎng)站教程第四章 前臺(tái)欄目瀏覽4.5
這篇文章主要為大家詳細(xì)介紹了MVC4制作網(wǎng)站教程,前臺(tái)欄目瀏覽功能實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08asp.net使用jquery模板引擎jtemplates呈現(xiàn)表格
這篇文章主要介紹了asp.net使用jquery模板引擎jtemplates呈現(xiàn)表格的示例,大家參考使用吧2014-01-01SqlCommandBuilder類(lèi)批量更新excel或者CSV數(shù)據(jù)的方法
這篇文章主要介紹了SqlCommandBuilder類(lèi)批量更新excel或者CSV數(shù)據(jù)的方法,需要的朋友可以參考下2015-10-10詳解ASP.NET Core WebApi 返回統(tǒng)一格式參數(shù)
這篇文章主要介紹了詳解ASP.NET Core WebApi 返回統(tǒng)一格式參數(shù),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-11-11