当前位置: 首页 > news >正文

.NET:自动将请求参数绑定到ASPX、ASHX和MVC(菜鸟必看)

前言

刚开始做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场景,其它场景也可以使用。

 

转载于:https://www.cnblogs.com/happyframework/archive/2013/04/28/3048648.html

相关文章:

  • Vim删除开头和结尾匹配的行
  • 模式对象设计模式Java实现(三)Strut2教程-java教程
  • 解惑:学.Net还是学Java?
  • 关于python写文件时的回车符
  • MOSS 2013研究系列---不常用函数总结……
  • 添加图片如何点击a标签, 弹出input file 上传文件对话框
  • (TOJ2804)Even? Odd?
  • Smack文档(翻译)转
  • UML 中关系详解以及在visio中的表示
  • linux下查找文件的常用命令
  • struts2-自定义拦截器
  • 敌兵布阵
  • Mac系统如何显示和隐藏文件
  • 无法读取配置节system.web.extensions,因为它缺少节声明
  • 【语言处理与Python】3.3使用Unicode进行文字处理
  • 【108天】Java——《Head First Java》笔记(第1-4章)
  • DataBase in Android
  • JavaScript设计模式与开发实践系列之策略模式
  • javascript数组去重/查找/插入/删除
  • JAVA并发编程--1.基础概念
  • Java知识点总结(JavaIO-打印流)
  • js操作时间(持续更新)
  • KMP算法及优化
  • SpiderData 2019年2月13日 DApp数据排行榜
  • Zsh 开发指南(第十四篇 文件读写)
  • 安装python包到指定虚拟环境
  • 复习Javascript专题(四):js中的深浅拷贝
  • 力扣(LeetCode)965
  • 面试遇到的一些题
  • 如何学习JavaEE,项目又该如何做?
  • 山寨一个 Promise
  • 什么软件可以剪辑音乐?
  • 通过几道题目学习二叉搜索树
  • 推荐一款sublime text 3 支持JSX和es201x 代码格式化的插件
  • 与 ConTeXt MkIV 官方文档的接驳
  • 自动记录MySQL慢查询快照脚本
  • 看到一个关于网页设计的文章分享过来!大家看看!
  • 策略 : 一文教你成为人工智能(AI)领域专家
  • $.ajax()方法详解
  • (23)Linux的软硬连接
  • (4)STL算法之比较
  • (42)STM32——LCD显示屏实验笔记
  • (arch)linux 转换文件编码格式
  • (PHP)设置修改 Apache 文件根目录 (Document Root)(转帖)
  • (Redis使用系列) Springboot 实现Redis 同数据源动态切换db 八
  • (Redis使用系列) Springboot 在redis中使用BloomFilter布隆过滤器机制 六
  • (vue)页面文件上传获取:action地址
  • (ZT) 理解系统底层的概念是多么重要(by趋势科技邹飞)
  • (编译到47%失败)to be deleted
  • (第61天)多租户架构(CDB/PDB)
  • (翻译)terry crowley: 写给程序员
  • (附源码)ssm本科教学合格评估管理系统 毕业设计 180916
  • (附源码)ssm基于web技术的医务志愿者管理系统 毕业设计 100910
  • (附源码)ssm捐赠救助系统 毕业设计 060945
  • (入门自用)--C++--抽象类--多态原理--虚表--1020