日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

ASP.NET MVC 自定义模型绑定1 - 自动把以英文逗号分隔的 ID 字符串绑定成 Listint...

發(fā)布時間:2023/12/13 asp.net 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.NET MVC 自定义模型绑定1 - 自动把以英文逗号分隔的 ID 字符串绑定成 Listint... 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

直接貼代碼了:

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 = "保存成功" });}} }

?

謝謝瀏覽!

轉載于:https://www.cnblogs.com/Music/p/comma-separated-model-binder-in-asp-net-mvc.html

總結

以上是生活随笔為你收集整理的ASP.NET MVC 自定义模型绑定1 - 自动把以英文逗号分隔的 ID 字符串绑定成 Listint...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。