asp.net mvc强类型视图模型与multiselect

我想知道如何从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);
    }
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....