0

I recently ran into a problem within my MVC5 C# project where my dynamically generated HTML elements (a collection of phone numbers) could be posted to the server where indexes were missing. Like this, missing [1]:

ClientInfo.Phones[0].PhoneNumber
ClientInfo.Phones[2].PhoneNumber
ClientInfo.Phones[3].PhoneNumber

When the page has more than one to add, or if a user manually adds another, the incremental numbering increases for the dynamic elements. But when a user deletes, say dynamic element [1], then there's a missing element in the collection. When the form is posted to the server the method that receives expects a class called ClientInfo, with an IEnumerable property, among lots of other stuff. When they index values are in order (0,1,2,3,...) everything serializes as expected into this Phones collection property. When one is missing, as in the example above, only those that are numbered, in order from 0 will serialize. In this case, index 2, 3 wouldn't be included, only [0].

I can see all the values and their index number in Fiddler when posting the form, so I know they're coming across the wire correctly. Is there a way to serialize these items despite them not having all the collection elements? Any help is appreciated! Thank you!

RichieMN
  • 905
  • 1
  • 12
  • 33
  • 1
    Can you instead of deleting an item just have its value set to null or empty , hide it and then handle that in c#? Then the indexed item will still exsist and you can just skip over null or empty values.. alternatively look at what your inputs looks like and how they are named in the actual html that posts to the server and when deleting just renamed your inputs accordingly on the client in order to have a concecutive array posted to the server. – Harry Sep 26 '17 at 20:11
  • Yes you can, but you need to show your code for how how your generating your dynamic html –  Sep 26 '17 at 22:22

0 Answers0