0

I´m trying to get single value out of an object array and display it for now inside paragraph tag on my index page.

In my HomeController I have done this

public ActionResult Index()
    {

        WebClient client2 = new WebClient();
        Stream stream = client2.OpenRead("http://localhost/ARN/weatherAPI.json");
        StreamReader reader = new StreamReader(stream);

        Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine());
        // instead of WriteLine, 2 or 3 lines of code here using WebClient to download the file
        var weatherString = (string)jObject["weather"][0]["main"];
        stream.Close();
return View();

I started by creating a new project in Console Application to test it and I ran this lines of code but used Console.Writeline(weatherString) and it gave me exactly the value I needed in the console but now I'm facing the problem to try to show it on the index page with the ASP.NET MVC

Since this piece of code is in my HomeController and my Index.cshtml is elsewhere, is there an easy way for me to output the weatherString variable as an simple text on my index page?

The JSON looks like this:

     "weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]

So I wan't "Rain" to be outputted on my webpage.

4
  • 2
    You can pass it to the view using ViewBag or the model Commented Jan 12, 2015 at 15:37
  • Is there a specific reason why you're fetching the JSON file in the view's controller rather than client-side? Commented Jan 12, 2015 at 15:39
  • Hi @Klors, No not really. I'm still in the learning process of ASP.NET so it's there mainly because I didn't know if it was better saved elsewhere. Commented Jan 12, 2015 at 15:41
  • 1
    I see, there's nothing really wrong with it, but I ask as there are client-side asynchronous JavaScript techniques for consuming JSON data that seem more "natural". As a data-store it's probably as good as anything though and fairly portable if you do decide to use it in JavaScript later. Commented Jan 12, 2015 at 15:47

1 Answer 1

1

You'll probably want it in your ViewBag. In the controller:

ViewBag.WeatherString = weatherString;

then in the view access it with @ViewBag.WeatherString

Alternatively you can use it as the view's model:

return View(weatherString)

and in your view:

model string

but thats pretty overkill

Sign up to request clarification or add additional context in comments.

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.