0

I am trying to serialize an ICollection to JSON and pass it to my JS via hidden field on my HTML.

So far I have tried:

  1. @Html.HiddenFor(model => JsonConvert.SerializeObject(model.Details), new { Id = "WorkOrderDetails" }) // also tried model.Details.ToArray(). model.Details.ToList()

  2. var jsonSerialiser = new JavaScriptSerializer(); @Html.HiddenFor(model => jsonSerialiser.Serialize(model.Details), new { Id = "WorkOrderDetails" }) // also tried model.Details.ToArray(). model.Details.ToList()

It complains about an Incompatibility error: InvalidOparationException

I am thinking at this pace I will need to iterate my ICollection and pass every single detail individually.

Is there a better way to do it?

Guillermo Sánchez
  • 143
  • 1
  • 3
  • 15

1 Answers1

1

HiddenFor is just a convenience method that helps in simple cases where you're going to pass it a simple expression like m => m.Details. Since this is more complicated, it's probably simpler to write your own HTML tag.

<input type="hidden" name="Details" 
    value="@jsonSerialiser.Serialize(model.Details)">
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315