博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET MVC 下自定义模型绑定,去除字符串类型前后的空格
阅读量:5371 次
发布时间:2019-06-15

本文共 3902 字,大约阅读时间需要 13 分钟。

直接贴代码了:

SkyModelBinder.cs

using System.ComponentModel;using System.Linq;using System.Web.Mvc;namespace MvcSample.Extensions{    public class SkyModelBinder : DefaultModelBinder    {        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)        {            var model = base.BindModel(controllerContext, bindingContext);            if (model is BaseSkyViewModel)            {                ((BaseSkyViewModel)model).BindModel(controllerContext, bindingContext);            }            return model;        }        protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext,            PropertyDescriptor propertyDescriptor, object value)        {            //check if data type of value is System.String            if (propertyDescriptor.PropertyType == typeof(string))            {                //developers can mark properties to be excluded from trimming with [NoTrim] attribute                if (propertyDescriptor.Attributes.Cast().All(a => a.GetType() != typeof (NoTrimAttribute)))                {                        var stringValue = (string)value;                        value = string.IsNullOrEmpty(stringValue) ? stringValue : stringValue.Trim();                }            }            base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);        }    }}

 

BaseSkyViewModel.cs

using System.Collections.Generic;using System.Web.Mvc;namespace MvcSample.Extensions{    ///     /// Base sky view model    ///     [ModelBinder(typeof(SkyModelBinder))]    public partial class BaseSkyViewModel    {        public BaseSkyViewModel()        {            this.CustomProperties = new Dictionary
(); PostInitialize(); } public virtual void BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { } ///
/// Developers can override this method in custom partial classes /// in order to add some custom initialization code to constructors /// protected virtual void PostInitialize() { } ///
/// Use this property to store any custom value for your models. /// public Dictionary
CustomProperties { get; set; } } ///
/// Base Sky entity model /// public partial class BaseSkyEntityViewModel : BaseSkyViewModel { public virtual int Id { get; set; } }}

 

NoTrimAttribute.cs

using System;namespace MvcSample.Extensions{    ///     /// Attribute indicating that entered values should not be trimmed    ///     public class NoTrimAttribute : Attribute    {    }}

 

DEMO

ProductInfoModifyViewModel.cs

using MvcSample.Extensions;using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace MvcSample.Models{    public class ProductInfoModifyViewModel : BaseSkyViewModel    {        public int ProductId { get; set; }        ///         /// 假设有一个这个 Property        ///         public string ProductName { get; set; }        public int NewYear { get; set; }    }}

HomeController.cs

using MvcSample.Extensions;using MvcSample.Models;using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace MvcSample.Controllers{    public class HomeController : Controller    {        [HttpPost]        public ActionResult ModifyProduct(ProductInfoModifyViewModel viewModel,            [ModelBinder(typeof(CommaSeparatedModelBinder))] List
orderStatusIds = null) { ProductInfoService.TryModifyById(viewModel.ProductId, viewModel.NewYear); return Json(new { Success = true, Message = "保存成功" }); } }}

 

运行截图:

 

图2:

 

谢谢浏览!

转载于:https://www.cnblogs.com/Music/p/custom-model-binder-for-trim-string-in-asp-net-mvc.html

你可能感兴趣的文章
nginx源码学习资源(不断更新)
查看>>
【bzoj2882】工艺 后缀自动机+STL-map
查看>>
[redis] redis
查看>>
Linux的加密认证功能以及openssl详解
查看>>
[Tools] 使用XP远程登录Win8系统
查看>>
【RL-TCPnet网络教程】第38章 TFTP简单文件传输基础知识
查看>>
HDU- 2265 Encoding The Diary
查看>>
socket基本概念
查看>>
[第三方]SCNetworkReachability 获取网络状态控件使用方法
查看>>
在Windows上使用putty连接一台Linux主机
查看>>
Socket常见错误
查看>>
百度地图2.0API和3.0API。你想要的百度地图的这都有
查看>>
专业词汇
查看>>
星期五的收获
查看>>
proxmox 去除订阅提示
查看>>
使用Html.EditorFor()为文本框加上maxlength,placeholder等属性
查看>>
[转]后缀数组求最长重复子串
查看>>
设计模式——外观模式详解
查看>>
MVC3 控件
查看>>
mysql (一)
查看>>