David
David

Reputation: 41

How to use json data in MVC view .cshtml

I hope someone can help me: My challenge is, that I have a web service returning a json.

The format is

{"stations":[{"name":"aname","free":false},{"name":"anothername","free":true}]}

so I have one object which is an array that hold n objects with n attributes.... Now for each object in that array of the stations object I would like to render the attributes, like

<p>stations[0].name</p>

I need to use this in mvc. So I created a model

public station(){}
public string name {get; set;}
public boolean free {get; set;}

in my contorller I use a WebClient and now I need to handle the response. I was thinking of IEnumerable but I don't know how to put this in the view?!

my goal is to understand how i can do something like

public Actionresult Stations(){
var stations = JObject.Load(reponse);
return View(Stations);
}

but I have no idea how to the handle each object of the array and get their values in the Stations.cshtml view using for each or similar....

Any idea?

Upvotes: 1

Views: 18977

Answers (4)

Manoj Raval
Manoj Raval

Reputation: 1

  1. Model data convert to Json format in controller

    JsonResult result = new JsonResult();
    result.Data = model;
    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    return result;
    
  2. In the view get Json data in TextBox

    $.ajax(
                {
                    type: 'POST',
                    url: "/Student/GetStudent",
                    data: { ID: ID },               
                    dataType: "json",
                    success: function (result) {
                        $("#StudentName").val(result.StudentName);
                        $("#Gender").val(result.Gender);
                        $("#Email").val(result.Email);    
                }    
     })
    

Upvotes: 0

Omar Muscatello
Omar Muscatello

Reputation: 1301

There are many ways to do that, this is my way.

Model

Create a class in which your JSON will be deserialized to:

public class RootJson
{
    public IEnumerable<station> Stations { get; set; }
}

The RootJson class has a property which will contain a list of station's instances (your class):

public class station
{
    public string name { get; set; }
    public bool free { get; set; }
}

Controller

Then, deserialize your JSON using:

var deserialized = JsonConvert.DeserializeObject<RootJson>(json);

And pass the stations to the view:

return View(deserialized.Stations);

View

In your view you have to specify the type of the data passed, in this case IEnumerable<station>. So, at the top of your Stations.cshtml add:

@model IEnumerable<station>

You can use a foreach to iterate over the model:

@foreach(var station in Model)
{
    <p>@station.name</p>
}

Edit: Full code for clarification

Model

RootJson.cs

public class RootJson
{
    public IEnumerable<station> Stations { get; set; }
}

station.cs

public class station
{
    public string name { get; set; }
    public bool free { get; set; }
}

Controller

Inside YourController.cs

public ActionResult Stations() {
    string json = YourMethodToGetJsonAsString();
    var deserialized = JsonConvert.DeserializeObject<RootJson>(json);
    return View(deserialized.Stations);
}

View

Stations.cshtml

@model IEnumerable<station>

@foreach(var station in Model)
{
    <p>@station.name</p>
}

Upvotes: 3

codejockie
codejockie

Reputation: 10864

Model

public class Stations
{
    public List<Station> Station { get; set; }
}
public class Station
{
    public string Name { get; set; }
    public bool Free { get; set; }
}

Controller

// Deserialising JSON
var station = JsonConvert.DeserializeObject<Stations>(response);
// Pass result to view
return View(station.Station);

View

At the top of your Stations.cshtml add:

@model IEnumerable<Station>

You can use a foreach to iterate over the model:

@foreach(var station in Model)
{
    <p>@station.Name</p>
}

Upvotes: 0

Logman
Logman

Reputation: 4189

One of simplest way is to use ViewBag like this:

public ActionResult Stations()
{
    string jsonString = "{ \"stations\":[{\"name\":\"aname\",\"free\":false},{\"name\":\"anothername\",\"free\":true}]}";
    ViewBag.stations = ((dynamic)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString)).stations;
    return View();
}

and inside cshtml for ex.

<p>@ViewBag.stations[0].name</p>

Upvotes: 0

Related Questions