【发布时间】:2013-03-11 13:35:52
【问题描述】:
小问题:
如果我为我的对象提供了一种隐式转换机制,可以将其值从纯字符串转换,是否可以使其自动绑定到 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; }
}
并且我的Controller中的Action设置为
// 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 变量更改为纯字符串,然后进行手动转换。
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-4