0

I'm trying to make a dynamic JSON OBJECT using razor but i don't know how to create the last child item without ','. I'm creating the last object writing, but it give me any issues.

I'm getting data from an Oracle database, with all parents and childs levels defined on data columns.

A short code simulating my code:

@{ 
var itemLevel = Model.LstUnidadesGerenciais.ElementAt(0).Level;
}

var treeData = [

    @foreach (var item in Model.LstUnidadesGerenciais)
    {
        var itemUG = item.Cod_UG; if (itemLevel == item.Level)
        { 
    <text>
        {
            title: "@item.Nome - @item.Txt_Sigla_UG", key: "@item.Level", icon: false, ug: "@item.Cod_UG", sigla: "@item.Txt_Sigla_UG", expand: true,
            children: [

                @foreach (var itemFilho in Model.LstUnidadesGerenciais)
                {
                    var itemUGFilho = itemFilho.Cod_UG; if (itemFilho.Cod_UG_Superior == itemUG && itemFilho.Level == item.Level + 1)
                    { 
                <text>
                {
                    title: "@itemFilho.Nome - @itemFilho.Txt_Sigla_UG", key: "@itemFilho.Level", icon: false, ug: "@itemFilho.Cod_UG", sigla: "@itemFilho.Txt_Sigla_UG", expand: false
                },
                </text>
                    }
                }

                {
                    title: "Nome", key: "2", icon: false, ug: "COD", sigla: "COD", expand: false
                }
            ]
        },

     </text>

        }
    }

     {
         title: "Nome", key: "1", icon: false, ug: "COD", sigla: "COD", expand: false
     }
];

I don't wanna to write this at end of an 'foreach' to solve the ',' problem:

     {
         title: "Nome", key: "1", icon: false, ug: "COD", sigla: "COD", expand: false
     }
Joao Paulo
  • 1,083
  • 4
  • 17
  • 36

1 Answers1

0

If you want to do this directly inside of the response, the following might be one way to do it:

 JavaScriptSerializer serializer = new JavaScriptSerializer();
 string json = serializer.Serialize((object)yourDictionary);

Credit to (Outputting Json with the Razor view engine) for this option. Alternatively if you are ok with using AJAX, in MVC4 (at least) you can just write the following

    // GET: /Account/
    [HttpGet]
    public ActionResult Index()
    {
       object myObject = LoadFromDatabase();
       return Json(myObject);
    }

In this "LoadFromDatabase" represents whatever you need in order to load from the database. The Json call serializes the object in standard JSON format for you (see msdn for more information).

This code goes into the controller and can be called from your javascript using AJAX. This might mean more round trips to the server but it can make page load times faster as your page isn't going to have to wait for the database call and json creation in order to return with the view.

Community
  • 1
  • 1
drew_w
  • 10,320
  • 4
  • 28
  • 49