在MVC系统中,我们接受数据,运用的是ModelBinder 的技术。
MVC学习系列——ActionResult扩展在这个系列中,我们自定义了
那么是不是意味着能POST一个
新建
1 public class 2 { 3 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 4 { 5 try 6 { 7 var modelType = bindingContext.ModelType; 8 var serializer = new 9 var inputStream = controllerContext.HttpContext.Request.InputStream;10 return serializer.Deserialize(inputStream);11 }12 catch (Exception)13 {14 throw;15 }16 }17 }
在HomeController的Post
1 public typeof(2 {3 viewModel.Name = "Result";4 //再次以5 return new 6 }
用Fiddler模拟一个以
接受数据:
因为viewModel.Name = "Result";
所以,在Fiddler中查看返回数据:
就这样,简单实现了:能够接收
但是,这样做带来一个问题,就是每次需要
那么问题来了:MVC能不能自动识别。这个问题的答案是肯定的。
新建
1 public class 2 { 3 public IModelBinder GetBinder(Type modelType) 4 { 5 var contentType = HttpContext.Current.Request.ContentType.ToLower(); 6 7 //如果不是Text/ 8 if (contentType!="text/") 9 {10 return null;11 }12 13 return new 14 }15 }
同时要注意的是:在Global类中,得注入。
1 protected void Application_Start() 2 { 3 AreaRegistration.RegisterAllAreas(); 4 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 5 RouteConfig.RegisterRoutes(RouteTable.Routes); 6 BundleConfig.RegisterBundles(BundleTable.Bundles); 7 8 //加载配置文件 9 var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "Log4Net.config");10 11 12 //13 ModelBinderProviders.BinderProviders.Insert(0, new 14 }
新建一个Action,Post
1 public 2 {3 viewModel.Name = "Post";4 //再次以5 return new 6 }
用fiddle进行模拟请求:
接受数据:
因为 viewModel.Name = "Post";
,所以fiddle返回数据:
原标题:MVC学习系列——ModelBinder扩展
关键词:mvc