【问题标题】:Can a QueryString parameter be bound to a complex object if the complex object has implicit casting from string如果复杂对象具有来自字符串的隐式转换,QueryString 参数是否可以绑定到复杂对象
【发布时间】: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


    【解决方案1】:

    不,默认模型绑定器不使用任何隐式运算符。您必须为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());
    

    【讨论】:

    • 我不会在我的视图模型上使用任何枚举或隐式运算符。
    • 好的,我可以理解您不推荐使用枚举和复杂对象的原因。谢谢。
    猜你喜欢
    • 2022-06-25
    • 2011-03-19
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多