如何显示数据到前端?

时间:2019-05-31 21:37:03

标签: c# asp.net-mvc

我是新手,不了解如何实施开放天气API。我不完全知道如何在剃刀视图中显示数据。因此,如果我想显示温度,我将如何做。我不想使用Viewbag来显示数据。

我在剃刀视图中使用一个元组来实现2个模型。使用邮政编码作为输入的openweatherModel。另一个是RootObject,它是Json.cs中的一个类,用于保存json信息,例如temp,coord,description等。

Api

public class ApiController 
    {
        public async Task<Json.RootObject> GetResult(int zipCode)
        {
            const string apiKey = "";
            var client = new HttpClient();


            var response = await client.GetAsync("http://api.openweathermap.org/data/2.5/weather?zip=" +
                                                 zipCode + ",us&APPID=" + apiKey);
            response.EnsureSuccessStatusCode();

            var responseBody = await response.Content.ReadAsStringAsync();

            return JsonConvert.DeserializeObject<Json.RootObject>(responseBody);
        }

首页

 [HttpGet]
        public ActionResult Main()
        {
            return View();
        }
        [HttpPost]
        public async Task<ActionResult> Main(int zipCode)
        {
             var controller = new ApiController();

            var rootObject = await controller.GetResult(zipCode);

           var tuple = new Tuple<OpenWeatherMap, RootObject>(new OpenWeatherMap(), new RootObject());

            return View(tuple);
        }

剃刀

@model  Tuple<Weather.Models.OpenWeatherMap, Weather.HelperClasses.Json.RootObject>
 <div>

        @using (Html.BeginForm("Main", "Home", FormMethod.Post, new { @class = "container" }))
        {


            @Html.TextBoxFor(tuple =>tuple.Item1.zipCode, new {@Name = "zipCode", @class = "inputs", required = "Required", placeholder = "Enter ZipCode" })

            <input id="submit" type="submit" value="Search" />

            foreach (var items in Model.Item2.weather)
            {
                <h1>@items.description</h1>
            }
        }
    </div>

RootObject

 public class RootObject
        {
            public Coord coord { get; set; }
            public List<Weather> weather { get; set; }
            public string @base { get; set; }
            public Main main { get; set; }
            public int visibility { get; set; }
            public Wind wind { get; set; }
            public Clouds clouds { get; set; }
            public int dt { get; set; }
            public Sys sys { get; set; }
            public int timezone { get; set; }
            public int id { get; set; }
            public string name { get; set; }
            public int cod { get; set; }
        }

0 个答案:

没有答案