Custom Model Binder for Complex composite objects HELP

前端 未结 2 460
太阳男子
太阳男子 2020-12-17 00:12

I am trying to write a custom model binder but I\'m having great difficulty trying to figure how to bind complex composite objects.

this is the class I\'m trying to

相关标签:
2条回答
  • 2020-12-17 00:52

    Do you really need to implement a custom ModelBinder here? The default binder may do what you need (as it can populate collections and complex objects):

    Lets say your controller action looks like this:

    public ActionResult SomeAction(Fund fund)
    {
      //do some stuff
      return View();
    }
    

    And you html contains this:

    <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" />
    

    The default model binder should initialise your fund object with 2 items in the FundAllocations List (I don't know what your FundAllocation class looks like, so I made up a single property "SomeProperty"). Just be sure to include those "fund.FundAllocations.Index" elements (which the default binder looks at for it's own use), that got me when I tried to get this working).

    0 讨论(0)
  • 2020-12-17 01:01

    I have been spending too much on this exact same thing lately!

    Without seeing your HTML form, I am guessing that it is just returning the results of selection from a multi select list or something? If so, your form is just returning a bunch of integers rather than returning your hydrated FundAllocations object. If you want to do that then, in your custom ModelBinder, you're going to need to do your own lookup and hydrate the object yourself.

    Something like:

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

    Of course, my LINQ is only for example and you obviously can retrieve the data anyway that you want. Incidentally, and I know that it doesn't answer your question but after much faffing around I have decided that for complex objects, I am best to use a ViewModel and have the default ModelBinder bind to that and then, if I need to, hydrate the model which represents my entity. There are a number of issues that I ran into which made this the best choice, I won't bore you with them now but am happy to extrapolate if you wish.

    The latest Herding Code podcast is a great discussion of this as are K Scott Allen's Putting the M in MVC blog posts.

    0 讨论(0)
提交回复
热议问题