2010-01-05 74 views
6

我想知道我可以如何绑定我的表单值到我的强类型的多选框中的视图。asp.net mvc强类型与多选视图模型

很显然,当表单提交多选框时,将提交一个被选中的值的字符串...将这个值的字符串转换回附加到我的模型的对象列表的最佳方法是什么更新?

public class MyViewModel { 
    public List<Genre> GenreList {get; set;} 
    public List<string> Genres { get; set; } 
} 

当更新我的控制器内部模型我使用的UpdateModel象下面这样:

Account accountToUpdate = userSession.GetCurrentUser(); 
UpdateModel(accountToUpdate); 

不过,我需要从字符串某种方式得到的值回对象。

我相信它可能与模型粘合剂有关,但我找不到任何明确的例子来说明如何做到这一点。

谢谢! Paul

回答

3

你是正确的,模型活页夹是要走的路。试试这个......

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, bindingContext, propertyDescriptor, value); 
    } 
} 
0

检查出Phil Haacks blog post关于这个问题。我用它作为最近项目中多选择强类型视图的基础。

+0

haack的帖子是关于绑定的对象列表,而不是列表框...... – 2012-08-23 20:13:43

相关问题