简短问题:
如果我已经为我的对象提供了一个隐式转换机制来转换普通字符串的值,那么它是否可以自动绑定到viewmodel的属性?
细节:
public enum PrimaryScopeEnum { Pivot1,Pivot2 } public enum SecondaryScopeEnum { Entity1,Entity2,Entity3,Entity4 } public class DataScope { public PrimaryScopeEnum PrimaryScope { get; set; } public SecondaryScopeEnum SecondaryScope { get; set; } public static implicit operator DataScope ( string combinedScope ) { DataScope ds = new DataScope(); // Logic for populating Primary and Secondary Scope enums return ds; } }
我在我的视图模型中使用上面的对象如下:
public enum PageModeEnum { View,Add,Edit } public class displayInfoviewmodel { public string SetID { get; set; } public PageModeEnum PageMode { get; set; } public DataScope Scope { get; set; } }
我的控制器中的操作设置为
// Accessed with /MyController/displayInfo?SetID=22&PageMode=View&Scope=Pivot1 public virtual ActionResult displayInfo ( displayInfoviewmodel vm ) { // vm.SetID is 22 // vm.PageMode is PageModeEnum.View // vm.Scope is null return View ( vm ); }
我的问题出在Action中,即使我已经从字符串到DataScope类进行了隐式转换,但它在执行期间无法正确绑定.
我已经使用正在传递的值(此处为Pivot1)测试了铸件并且铸件工作正常.
有没有办法隐式地进行这种转换,或者我应该将视图模型Scope变量更改为plain string然后进行手动转换.
解决方法
不,默认模型绑定器不使用任何隐式运算符.您必须为DataScope类型编写自定义模型绑定器,并根据需要手动将其与请求字符串绑定.
例如:
public class DataScopeModelBinder : DefaultModelBinder { protected override object CreateModel(ControllerContext controllerContext,ModelBindingContext bindingContext,Type modelType) { var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (value == null) { return null; } return (DataScope)value.RawValue; } }
然后,您将与Application_Start中的DataScope类型关联:
ModelBinders.Binders.Add(typeof(DataScope),new DataScopeModelBinder());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。