How do I get my model in my view using C #?

I am deserializing my JSON response into an object. What are the next steps? I have a WebAPI controller that I am currently working with my JSON object. I need to take this data and move it into a view so that I can connect it to my web components.

I guess I'm confused if I should iterate over my JSON object in controller or view? I have the following:

var model = JsonConvert.DeserializeObject<MyData.RootObject>(Data);
foreach (var record in Data.rows)
{
    foreach (var nestedRecord in record.f)
    {
         List<string> list = new List<string>();
         list.Add(nestedRecord.v);         
    }
}
return View();

      

Also, I am iterating over this model and I cannot get the model back in the view since it is out of scope.

+3


source to share


1 answer


I see two popular options here, depending on how much information you can get from the deserialized object. First, use MyData.RootObject

as your model and iterate over it in view. This will give you the most flexibility if you need to access other properties of the object:

var model = JsonConvert.DeserializeObject<MyData.RootObject>(Data);
return View(model);

      

In a view (this unordered list markup is just a sample), you can have:

@model MyData.RootObject

<ul>
@foreach (var record in Model.rows)
{
    foreach (var nestedRecord in record.f)
    {
        <li>@nestedRecord.v</li>
    }
}
</ul>

      



Or, continue as you planned, but move the list you fill outside of the for-loops using the list as a model. This would be the least flexible in terms of rendering your object in the view:

var rootObject = JsonConvert.DeserializeObject<MyData.RootObject>(Data);
List<string> list = new List<string>();
foreach (var record in rootObject.rows)
{
    foreach (var nestedRecord in record.f)
    {
        list.Add(nestedRecord.v);         
    }
}
return View(list);

      

And your look in this case (much more concise than the other option):

@model System.Collections.Generic.List<string>

<ul>
@foreach (var record in Model)
{
    <li>@record</li>
}
</ul>

      

+3


source







All Articles