如何在MVC视图.cshtml中使用json数据

问题描述 投票:0回答:3

我希望有人可以帮助我:我的挑战是,我有一个返回json的Web服务。

格式是

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

所以我有一个对象是一个数组,用n属性保存n对象....现在对于该对象的数组中的每个对象,我想渲染属性,如

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

我需要在mvc中使用它。所以我创建了一个模型

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

在我的控制器中,我使用WebClient,现在我需要处理响应。我在想IEnumerable,但我不知道怎么把它放在视图中?!

我的目标是了解我可以做些什么

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

但我不知道如何处理数组的每个对象,并在Stations.cshtml视图中使用每个或类似的....

任何的想法?

c# json asp.net-mvc
3个回答
1
投票

有很多方法可以做到这一点,这是我的方式。

Model

创建一个类,在其中将JSON反序列化为:

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

RootJson类有一个属性,其中包含station实例列表(您的类):

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

Controller

然后,使用以下命令反序列化您的JSON:

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

并将站点传递到视图:

return View(deserialized.Stations);

View

在您的视图中,您必须指定传递的数据类型,在本例中为IEnumerable<station>。所以,在你的Stations.cshtml顶部添加:

@model IEnumerable<station>

您可以使用foreach迭代模型:

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

编辑:完整的代码以便澄清

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

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

0
投票

最简单的方法之一就是像这样使用ViewBag:

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

并在内部的cshtml中。

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

0
投票

模型

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

调节器

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

视图

在你的Stations.cshtml顶部添加:

@model IEnumerable<Station>

您可以使用foreach迭代模型:

@foreach(var station in Model)
{
    <p>@station.Name</p>
}
© www.soinside.com 2019 - 2024. All rights reserved.