我想知道如何从MultiSelect框中将我的表单值绑定到我的强类型视图.
显然,当表单提交多选框时,会提交一个已选中的值的delittemered字符串…将这个值字符串转换回附加到我的模型要更新的对象列表的最佳方法是什么?
public class Myviewmodel { public List<Genre> GenreList {get; set;} public List<string> Genres { get; set; } }
在控制器内更新我的模型时,我正在使用UpdateModel,如下所示:
Account accountToUpdate = userSession.GetCurrentUser(); UpdateModel(accountToUpdate);
但是我需要以某种方式将字符串中的值返回到对象中.
我相信它可能与模型粘合剂有关,但我找不到任何明确的如何做到这一点的例子.
谢谢!!
保罗
解决方法
你是正确的,模型绑定器是要走的路.试试这个…
using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; [ModelBinder(typeof(MyviewmodelBinder))] public class Myviewmodel { .... } public class MyviewmodelBinder : DefaultModelBinder { protected override void SetProperty(ControllerContext context,ModelBindingContext bindingContext,PropertyDescriptor propertyDescriptor,object value) { if (propertyDescriptor.Name == "Genres") { var arrVals = ((string[])value)[0].Split(','); base.SetProperty(context,bindingContext,propertyDescriptor,new List<string>(arrVals)); } else base.SetProperty(context,value); } }