基于.NET中:自动将请求参数绑定到ASPX、ASHX和MVC的(2)


/// <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#" %>

 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; }
 }


运行结果

自动绑定到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);
         }
     }
 }


您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjgxpf.html