c# – 如果复杂对象具有来自字符串的隐式转换,则QueryString参数
发布时间:2020-12-15 07:54:06 所属栏目:百科 来源:网络整理
导读:简短问题: 如果我已经为我的对象提供了一个隐式转换机制来转换普通字符串的值,那么它是否可以自动绑定到ViewModel的属性? 细节: 我有一个像这样的复杂对象(简化为了简洁和清晰) public enum PrimaryScopeEnum { Pivot1,Pivot2}public enum SecondaryScope
简短问题:
如果我已经为我的对象提供了一个隐式转换机制来转换普通字符串的值,那么它是否可以自动绑定到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()); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |