2

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?

1
  • is that web service deployed in the same domain? Commented Dec 16, 2017 at 15:34

4 Answers 4

3

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>
}
Sign up to request clarification or add additional context in comments.

15 Comments

So I actually make 2 models, one for the jsonand one for the stations in the json? I wil try that tomorrow!! Thx!!
Thank you so much for your help, @omaxel!.
Unfortunately i still get the problem not beeing able to use IEnumerable in my view. IDE tells me, that <station> (as type or namespace) can not be found when using '@model IEnumerable<station> in the controller it knows station as IEnumerable<station> of RootJson.Stations, but not in the view.....
Yes and no. Theoretically you have a model which is wrapped in class because of your JSON.
When using a model in a view you should use the full namespace too. So, make sure your station is accesible from the view. For example, if your namespace in which the class is declared is WebApplication1.Models, then in your view you have to use IEnumerable<WebApplication1.Models.station. Hope it helps.
|
0

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>

3 Comments

To much hard coding.
I don't know ViewBag, so I will look into it, but: I would replace the string here with response, right?
It depends on what your response is. If it is a string you may simple use it instead of jsonString. If it is something else you need to convert it to object model.
0

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

2 Comments

Hi, thanks so much for answering! I guess <Users> is a typo? I will try tomorrow and let you know!
Yeah, it is a typo. Corrected it.
0
  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);    
                }    
     })
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.