0

I have a ViewModel with a List<Section> Sections in it, my clients can send null values in this collection, I want to initialize them with default constructor of Section.

How can it be done for all Collections in ViewModels at once?

I'm trying to achieve this with extending DefaultBinder - but the problem is that CreateModel is not called for a null

Anarion
  • 2,406
  • 3
  • 28
  • 42
  • What do you mean they can send null values? Do you mean some properties of `Section` are `null`? –  Dec 20 '16 at 22:27
  • 1
    so you don't want a default instance nor do you want nulls. how does that work? – Steve Dec 20 '16 at 22:27
  • Json is sent from clients, and I can have an array with null in this json, something like Sections: [null] – Anarion Dec 20 '16 at 22:28
  • @Steve - I do want a default instance. – Anarion Dec 20 '16 at 22:28
  • @Anarion then you either initialize them with default constructor of Section or you can make a variable to store an empty instance of section and add it to the list. But at the end of the day you are either checking == null or == EmptySection – Steve Dec 20 '16 at 22:30
  • Where do I initialize them? I was debugging CreateModel of my class that extends DefaultModelBinder, and I never hit a model of collection elements. – Anarion Dec 20 '16 at 22:32
  • Is it feasible to just make `Section` a struct instead of a class? That would be the easiest solution. – recursive Dec 20 '16 at 22:34
  • Unfortunatelly it's a complex class, I don't think switching to struct is a good option – Anarion Dec 20 '16 at 22:35
  • Added last paragraph trying to explain better what I'm doing. – Anarion Dec 20 '16 at 22:37
  • What are you wanting to achieve? If the client sends `Sections: [null]` which will initialize your collection property with one `null` item, do you want to remove that item (so its an empty collection), or do you want to replace the `null` instance with a default instance? –  Dec 20 '16 at 22:39
  • @StephenMuecke, I want a default instance instead of null. – Anarion Dec 20 '16 at 22:41
  • Related, if not duplicate: http://stackoverflow.com/q/1207991/215552 – Heretic Monkey Dec 20 '16 at 22:42

0 Answers0