c# – 如果复杂对象具有来自字符串的隐式转换,则QueryString参数是否可以绑定到复杂对象

简短问题:

如果我已经为我的对象提供了一个隐式转换机制来转换普通字符串的值,那么它是否可以自动绑定到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());

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...