【问题标题】:MVC 3 custom ModelBinder not being used未使用 MVC 3 自定义 ModelBinder
【发布时间】:2011-02-11 15:45:18
【问题描述】:

我有一个发布一堆隐藏变量的表单,其中一些具有相同的名称。这是帖子正文:

OfferId=3802&DeliveryDate=11%2F02%2F2011&DeliveryTime=12%3A00&location=1&location=698

它将它发布到 MVC 操作:

[HttpPost]
public ActionResult DeliveryOptions(DeliveryOptions model)
{
    ...
}

DeliveryOptions 模型如下所示:

public class DeliveryOptions
{
    public long? OfferId { get; set; }

    [CustomValidation(typeof(CustomValidator), "IsDeliveryDateValid")]
    public DateTime? DeliveryDate { get; set; }

    public DateTime? DeliveryTime { get; set; }

    [CustomValidation(typeof(CustomValidator), "IsLocationsValid")]
    public OfferLocations Locations { get; set; }
}

现在,我想将发布的location 变量解析为 OfferLocations 对象,如下所示:

[ModelBinder(typeof(OfferLocationsModelBinder))]
public class OfferLocations
{
    [Required]
    public int[] LocationIds { get; set; }
}

模型绑定器当前如下所示:

public class OfferLocationsModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        throw new NotImplementedException();
    }
}

问题是,我无法打破 NotImplementedException。模型绑定器不执行。我可能错过了一些明显的东西;有什么想法吗?

【问题讨论】:

    标签: c# asp.net-mvc-3 modelbinders


    【解决方案1】:

    尝试从System.Web.Mvc.DefaultModelBinder 继承您的模型绑定器,并覆盖object BindModel(ControllerContext, ModelBindingContext) 方法。看看这是否有效。如果是这样 - 你可以从那里工作:)

    这就是我现在正在做的事情。基本上,我必须确保如果请求中有特定类型 - 针对该值执行方法。模型绑定器注册代码完全相同 - 应用于属性类的属性。

    模型绑定器如下:

    public class TableModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var result = base.BindModel(controllerContext, bindingContext) as ITableModel;
            if (result != null)
                result.UpdateSorter();
            return result;
        }
    }
    

    附:从基本模型绑定器派生为我提供了使用标准 Mvc 代码绑定所有属性的额外好处,然后我可以扩展反序列化对象:)

    希望对你有帮助

    【讨论】:

    • 在我的解决方法中使用了这种方法。工作完美,因为我将发布的变量更改为 CSV 字符串。
    【解决方案2】:

    该 ModelBinder 是否已向 DepedencyResolver 注册?我想知道 MVC 是否在找到您的 ModelBinder 时遇到问题,并且正在使用默认的。

    【讨论】:

    • 我尝试在 Global.asax Application_Start 中注册模型绑定器,但这没有帮助。此外,项目中还有其他几个自定义模型绑定器,它们看起来很像我的,并且它们可以工作。我只是不明白为什么我的没有。我是否需要将 location 后变量重命名为其他变量?
    【解决方案3】:

    无法让它工作。必须实施解决方法。

    我现在将位置 ID 作为 CSV 字符串发布,并且它们被自定义模型绑定器拾取,因此可以解析到数组中。很遗憾我不能以其他方式做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      • 2011-08-30
      相关资源
      最近更新 更多