直接贴代码了:
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
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 DictionaryCustomProperties { 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:
谢谢浏览!