-3

I have these Models.

public class ModelA
{
  List<ModelB> ModelB {get;set;}
}

public class ModelB
{
  List<ModelC> ModelC {get;set}
}

Now, I tried to convert in my script the models above base from this answer in my view.

<script>
        var modelB = '@Html.Raw(Json.Encode(Model.ModelB))';
        var modelBData = JSON.parse(modelB);

        // Here comes the problem...
        var modelC = '@Html.Raw(Json.Encode(Model.ModelB.ModelC))';

</script>

I can convert the Model B to javascript array but failed to convert ModelC into a javascript array. Now, how can I convert the list of ModelC in ModelB into a javascript array? I was hoping someone might be able to spot where i'm going wrong.

progammer101
  • 47
  • 1
  • 8
  • Let's say `ModelA` contained three `ModelB` items. The first `ModelB` contains one `ModelC`. The second `ModelB` contains two `ModelC`. The third contains three. How many `ModelC` items are you expecting to see in your `Here comes the problem` JSON? – mjwills Aug 13 '17 at 13:36
  • I need it all actually. I think you're not getting my point – progammer101 Aug 13 '17 at 13:58
  • Can you update your post with the generated HTML (View Source in your browser) for the `modelB` and `modelBData` lines? (after commenting out `var modelC` and other lines that don't compile) – mjwills Aug 13 '17 at 14:12
  • Could you include the generated HTML @progammer101 ? – mjwills Aug 14 '17 at 05:21

1 Answers1

0
var modelC = '@Html.Raw(Json.Encode(Model.ModelB.ModelC))';

should be changed to:

var modelC = '@Html.Raw(Json.Encode(Model.ModelB.SelectMany(z => z.ModelC)))';

The SelectMany will mean you serialise all ModelC objects that occur in any of the ModelB objects.

mjwills
  • 23,389
  • 6
  • 40
  • 63
  • Thanks, but what if the scenario is. I need to serialize All ModelC objects per ModelB objects – progammer101 Aug 13 '17 at 14:08
  • It didn't work, sorry for the late reply. i tried using alert on each item on ModelC and shows 'undefined' – progammer101 Aug 13 '17 at 15:15
  • `var ModelC = '@Html.Raw(Json.Encode(Model.ModelB.SelectMany(m => m.ModelC)))';``var modelC = JSON.parse(modelC);` `$.each(modelC, function () { alert(ModelC.Description); });` – progammer101 Aug 14 '17 at 02:39
  • jquery's `each` doesn't work like that (to be explicit - you are using `ModelC` variable without declaring it). Look at the `// Outputs: one two three` example at https://www.sitepoint.com/jquery-each-function-examples/ . – mjwills Aug 14 '17 at 05:20