【问题标题】:asp.net mvc strongly typed view model with multiselect具有多选的 asp.net mvc 强类型视图模型
【发布时间】:2011-01-01 20:05:17
【问题描述】:

我想知道如何将表单值绑定到多选框中的强类型视图。

显然,当表单提交时,多选框将提交我选择的值的 delittemered 字符串...将此值字符串转换回对象列表以附加到要更新的模型的最佳方法是什么?

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

在控制器内更新我的模型时,我使用如下 UpdateModel:

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

但是我需要以某种方式将字符串中的值返回到对象中。

我相信这可能与模型绑定器有关,但我找不到任何好的明确示例来说明如何做到这一点。

谢谢!! 保罗

【问题讨论】:

    标签: asp.net viewmodel modelbinders multi-select updatemodel


    【解决方案1】:

    你说得对,模型活页夹是要走的路。试试这个...

    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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      查看Phil Haacks blog post 的主题。我在最近的一个项目中使用它作为多选强类型视图的基础。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多