c# - 如果复杂对象具有从字符串隐式转换,则 QueryString 参数是否可以绑定(bind)到复杂对象

标签 c# asp.net-mvc asp.net-mvc-4

简短问题:

如果我已经为我的对象提供了一个隐式转换机制来将其值从纯字符串转换,是否可以使其自动绑定(bind)到 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;
    }
}

我在我的 View 模型中使用上面的对象如下:

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 类的隐式转换,它在执行期间也无法正确绑定(bind)。

我已经分别用传递的值(此处为 Pivot1)测试了转换,转换工作正常。

有没有办法使这种转换隐式发生,或者我应该将 View 模型 Scope 变量更改为纯字符串,然后进行手动转换。

最佳答案

不,默认模型绑定(bind)器不使用任何隐式运算符。您必须为 DataScope 类型编写一个自定义模型绑定(bind)器,如果您希望它起作用,则必须从请求字符串中手动绑定(bind)它。

例如:

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());

关于c# - 如果复杂对象具有从字符串隐式转换,则 QueryString 参数是否可以绑定(bind)到复杂对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15340005/

相关文章:

c# - 具有通用集合的 WCF REST 服务

c# - Excel 到 SQL、C# 库

asp.net-mvc - 在没有 IoC 容器的情况下如何对 Controller 进行单元测试?

javascript - Ajax调用angularJs调用方法

c# - 在 MVC 类上创建主键字段

c# - 在 C# 属性类的构造函数中,如何判断正在处理的属性目标?

c# - 用户凭据在 asp.net 网站中以明文形式发送

c# - 根据值选中或取消选中复选框?

asp.net-mvc-4 - 如何在 Durandal 中使用 cshtml 文件?

asp.net-mvc-3 - 如何在MonoDevelop中获取MVC 3或4模板?