2012-05-17 82 views
3

我使用的是最近发布的MVC 4 Beta版(4.0.20126.16343)和我努力让围绕一个已知的问题与反序列化/模型绑定无法与阵列(见Stack Overflow here把我的定制模型绑定到我的POST控制器

工作

我很难让我明确的自定义绑定挂钩。我已经注册了一个客户IModelBinder(或试图),但是当我的后处理操作被称为我的自定义绑定没有命中,我只是得到默认序列化(与空数组 - 即使wireshark显示我传入的复杂对象包含数组元素)。

我觉得我错过了一些东西,并会非常感谢任何解决方案或见解。

谢谢。

从的global.asax.cs:

public static void RegisterRoutes(RouteCollection routes) 
{ 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

    routes.MapHttpRoute(
     name: "DefaultApi", 
     routeTemplate: "api/{controller}/{id}", 
     defaults: new { id = RouteParameter.Optional } 
    ); 

    routes.MapRoute(
     name: "Default", 
     url: "{controller}/{action}/{id}", 
     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
    ); 
} 

protected void Application_Start() 
{ 
    ModelBinders.Binders.Add(typeof(DocuSignEnvelopeInformation), new DocusignModelBinder()); 
    AreaRegistration.RegisterAllAreas(); 

    RegisterGlobalFilters(GlobalFilters.Filters); 
    RegisterRoutes(RouteTable.Routes); 

    BundleTable.Bundles.RegisterTemplateBundles(); 
} 

,我的定制绑定:

public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext) 
{ 
    var value = bindingContext.ValueProvider.GetValue("envelope"); 

    var model = new DocuSignEnvelopeInformation(); 

    //build out the complex type here 

    return model; 
} 

和我的控制器就是:

public void Post(DocuSignEnvelopeInformation envelope) 
{ 
    Debug.WriteLine(envelope); 
} 

回答

1

这是我落得这样做(在Model binding XML in ASP.NET MVC 3感谢吉米·博加德)

我结束我的解决方案回MVC 3(由发行前的焦虑烧伤再次)

增加了ModelBinderProvider:

public class XmlModelBinderProvider : IModelBinderProvider 
{ 
    public IModelBinder GetBinder(Type modelType) 
    { 
     var contentType = HttpContext.Current.Request.ContentType; 

     if (string.Compare(contentType, @"text/xml", 
      StringComparison.OrdinalIgnoreCase) != 0) 
     { 
      return null; 
     } 

     return new XmlModelBinder(); 
    } 
} 

和ModelBinder的

public class XmlModelBinder : IModelBinder 
{ 
    public object BindModel(
     ControllerContext controllerContext, 
     ModelBindingContext bindingContext) 
    { 
     var modelType = bindingContext.ModelType; 
     var serializer = new XmlSerializer(modelType); 

     var inputStream = controllerContext.HttpContext.Request.InputStream; 

     return serializer.Deserialize(inputStream); 
    } 
} 

并将其添加到Application_Start()中:

ModelBinderProviders.BinderProviders 
    .Add(new XmlModelBinderProvider()); 

我的控制器保持与问题完全相同。

工程就像一种享受。当新的'没有字符串'的方法正确地到达MVC 4时会很棒,但是这种手动绑定的反序列化方法并不完全麻烦。

+0

我打算继续,并将自己的答案标记为已接受 - 因为这是我所做的工作。如果您的相关事情发生,请随时添加任何内容。 – reuben

2

我们一般通过注册我们的模型绑定DI容器,它的工作原理。使用DependencyResolver使用的DI容器注册一个IModelBinderProvider,并从GetBinder方法中返回您的ModelBinder。

+0

感谢您的回复。由于不值得进入的原因,我们不会去DI路径,所以这个选项对我来说是不可用的。当然值得赞赏,但我会坚持标志作为答案,因为我真的是在“样本代码”风格的答案之后。 我怀疑我真正的答案是等待MVC 4的下一个(RC?)版本,据说它包含自动绑定的修复。 – reuben

相关问题