在 ASP.NET MVC 中输出 JSON 值

Output JSON value in ASP.NET MVC

我正在尝试从对象数组中获取单个值并将其显示在我的索引页面上的段落标记内。

在我的 HomeController 中我已经这样做了

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();

我开始在控制台应用程序中创建一个新项目来测试它,我 运行 这行代码但使用了 Console.Writeline(weatherString) 它给了我我在控制台中需要的值但是现在我遇到了尝试使用 ASP.NET MVC

在索引页上显示它的问题

由于这段代码在我的 HomeController 中,而我的 Index.cshtml 在其他地方,有没有一种简单的方法可以让我在索引页面上将 weatherString 变量作为简单文本输出?

JSON 看起来像这样:

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

所以我不想"Rain"在我的网页上输出

您可能需要在 ViewBag 中使用它。在控制器中:

ViewBag.WeatherString = weatherString;

然后在视图中使用 @ViewBag.WeatherString

访问它

或者您可以将它用作视图的模型:

return View(weatherString)

在您看来:

model string

但这太过分了