Pau*_*ett 6 asp.net updatemodel modelbinders multi-select viewmodel
我想知道如何从MultiSelect框中将我的表单值绑定到我的强类型视图.
显然,当表单提交多选框时,会提交一个已选中的值的delittemered字符串...将这个值字符串转换回附加到我的模型要更新的对象列表的最佳方法是什么?
public class MyViewModel {
public List<Genre> GenreList {get; set;}
public List<string> Genres { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在控制器内更新我的模型时,我正在使用UpdateModel,如下所示:
Account accountToUpdate = userSession.GetCurrentUser();
UpdateModel(accountToUpdate);
Run Code Online (Sandbox Code Playgroud)
但是我需要以某种方式将字符串中的值返回到对象中.
我相信它可能与模型粘合剂有关,但我找不到任何明确的如何做到这一点的例子.
谢谢!!保罗
小智 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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1961 次 |
| 最近记录: |