ASP.NET MVC多选强类型视图模型

6
我想知道如何将我的表单值绑定到我强类型视图中的多选框。显然,当表单提交时,多选框将提交一个被删除的字符串,其中包含所选的值...将这些值转换回对象列表并附加到要更新的模型中的最佳方法是什么?请注意保留所有HTML标记。
public class MyViewModel {
    public List<Genre> GenreList {get; set;}
    public List<string> Genres { get; set; }
}

在控制器中更新模型的时候,我使用以下方式来使用UpdateModel:
Account accountToUpdate = userSession.GetCurrentUser();
UpdateModel(accountToUpdate);

然而我需要以某种方式将字符串中的值重新转换为对象。

我认为这可能与模型绑定器有关,但我找不到任何好的清晰示例来说明如何实现。

谢谢! 保罗

2个回答

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的博客文章。我在最近的一个项目中使用它作为多选强类型视图的基础。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接