-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.

4
  • 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
    CommentedAug 13, 2017 at 13:36
  • I need it all actually. I think you're not getting my pointCommentedAug 13, 2017 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
    CommentedAug 13, 2017 at 14:12
  • Could you include the generated HTML @progammer101 ?
    – mjwills
    CommentedAug 14, 2017 at 5:21

1 Answer 1

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 allModelC objects that occur in any of the ModelB objects.

4
  • Thanks, but what if the scenario is. I need to serialize All ModelC objects per ModelB objectsCommentedAug 13, 2017 at 14:08
  • It didn't work, sorry for the late reply. i tried using alert on each item on ModelC and shows 'undefined'CommentedAug 13, 2017 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); });CommentedAug 14, 2017 at 2: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 sitepoint.com/jquery-each-function-examples .
    – mjwills
    CommentedAug 14, 2017 at 5:20

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.