ASP.NET MVC 自定义模型绑定1 - 自动把以英文逗号分隔的 ID 字符串绑定成 List<int>
2018-12-19 18:17 音乐让我说 阅读(519) 评论(0) 编辑 收藏 举报直接贴代码了:
CommaSeparatedModelBinder.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web.Mvc; namespace MvcSample.Extensions { public class CommaSeparatedModelBinder : DefaultModelBinder { private static readonly MethodInfo ToArrayMethod = typeof(Enumerable).GetMethod("ToArray"); public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { return BindCsv(bindingContext.ModelType, bindingContext.ModelName, bindingContext) ?? base.BindModel(controllerContext, bindingContext); } protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { return BindCsv(propertyDescriptor.PropertyType, propertyDescriptor.Name, bindingContext) ?? base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); } private object BindCsv(Type type, string name, ModelBindingContext bindingContext) { if (type.GetInterface(typeof(IEnumerable).Name) != null) { var actualValue = bindingContext.ValueProvider.GetValue(name); if (actualValue != null) { var valueType = type.GetElementType() ?? type.GetGenericArguments().FirstOrDefault(); if (valueType != null && valueType.GetInterface(typeof(IConvertible).Name) != null) { var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(valueType)); foreach (var splitValue in actualValue.AttemptedValue.Split(new[] { ',' })) { if (!String.IsNullOrWhiteSpace(splitValue)) list.Add(Convert.ChangeType(splitValue, valueType)); } if (type.IsArray) return ToArrayMethod.MakeGenericMethod(valueType).Invoke(this, new[] { list }); return list; } } } return null; } } }
客户端测试 :
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(int productId, int newYear, [ModelBinder(typeof(CommaSeparatedModelBinder))] List<int> orderStatusIds = null) { ProductInfoService.TryModifyById(productId, newYear); return Json(new { Success = true, Message = "保存成功" }); } } }
谢谢浏览!
作者:音乐让我说(音乐让我说 - 博客园)
出处:http://music.cnblogs.com/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2011-12-19 调用百度“搜索建议(BaiduSuggestion)”的 API
2011-12-19 定义一个 GlobalSqlConfigHelper 类,实现读取 XML 文件中的 SQL 语句。
2011-12-19 关于 C# 中的 volatile 关键字