复杂复合对象的自定义模型粘合剂帮助

7 asp.net-mvc modelbinders

我正在尝试编写一个自定义模型绑定器,但我很难设法如何绑定复杂的复合对象.

这是我想要绑定的类:

public class Fund
{
        public int Id { get; set; }
        public string Name { get; set; }
        public List<FundAllocation> FundAllocations { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这就是我尝试编写自定义绑定器的方式:

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

    public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState)
    {
        var fund = new Fund();

        fund.Id = int.Parse(controllerContext.HttpContext.Request.Form["Id"]);
        fund.Name = controllerContext.HttpContext.Request.Form["Name"];

        //i don't know how to bind to the list property :(
        fund.FundItems[0].Catalogue.Id = controllerContext.HttpContext.Request.Form["FundItem.Catalogue.Id"];
        return fund;
    }
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗

谢谢Tony

Jon*_*noW 8

你真的需要在这里实现自定义ModelBinder吗?默认绑定器可以执行您需要的操作(因为它可以填充集合和复杂对象):

让我们说你的控制器动作如下:

public ActionResult SomeAction(Fund fund)
{
  //do some stuff
  return View();
}
Run Code Online (Sandbox Code Playgroud)

你的HTML包含这个:

<input type="text" name="fund.Id" value="1" />
<input type="text" name="fund.Name" value="SomeName" />

<input type="text" name="fund.FundAllocations.Index" value="0" />
<input type="text" name="fund.FundAllocations[0].SomeProperty" value="abc" />

<input type="text" name="fund.FundAllocations.Index" value="1" />
<input type="text" name="fund.FundAllocations[1].SomeProperty" value="xyz" />
Run Code Online (Sandbox Code Playgroud)

默认模型绑定器应该使用FundAllocations列表中的2个项目初始化您的基金对象(我不知道您的FundAllocation类是什么样的,所以我编写了一个属性"SomeProperty").只要确保包含那些"fund.FundAllocations.Index"元素(默认绑定器为它自己使用而查看),当我试图让它工作时,这就得到了我.


dav*_*ave 3

我最近在同样的事情上花了太多钱!

如果没有看到你的 HTML 表单,我猜它只是返回从多选列表或其他内容中选择的结果?如果是这样,您的表单只是返回一堆整数,而不是返回您的水合FundAllocations对象。如果您想这样做,那么在您的自定义 ModelBinder 中,您将需要自己进行查找并自行水合对象。

就像是:

fund.FundAllocations = 
      repository.Where(f => 
      controllerContext.HttpContext.Request.Form["FundItem.Catalogue.Id"].Contains(f.Id.ToString()); 
Run Code Online (Sandbox Code Playgroud)

当然,我的 LINQ 仅作为示例,您显然可以按照您想要的方式检索数据。顺便说一句,我知道它并没有回答你的问题,但经过一番折腾后,我决定,对于复杂的对象,我最好使用 ViewModel 并让默认的 ModelBinder 绑定到它,然后,如果我需要的话,水合代表我的实体的模型。我遇到了很多问题,这使得这是最好的选择,我现在不会让你厌烦这些问题,但如果你愿意的话,我很乐意推断。

最新的Herding Code 播客对此进行了精彩的讨论,K Scott Allen 的 Putting the M in MVC 博客文章也是如此。