Есть ли лучший или оптимизированный способ вернуть представление с моделью в контроллере, изменить форму модели, представление, контроллер и т. Д.? - PullRequest
0 голосов
/ 26 октября 2019

Мне не нужна косметическая работа, есть ли лучший способ сделать это, у меня есть некоторые сомнения при возврате View с контроллера на View с моделью .... Я надеюсь, что это будет лучше, ноЯ не могу этого сделать, пожалуйста, ведите меня.

Это представление.

@model MVCwithWebAPI.Models.RootObject
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<table>

    <tr>
        <td>
            <strong>
                <br />
                @Model.cod
            </strong>
        </td>


        <td>
            <strong>
                <br />
                @Model.wind.speed
            </strong>
        </td>

        <td>
            <strong>
                <br />
                @Model.dt
            </strong>
        </td>

        <td>
            <strong>
                <br />
                @Model.cod
            </strong>
        </td>

        <td>
            <strong>
                <br />
                @Model.name
            </strong>
        </td>
    </tr>
</table>

Это модель, созданная возвращением Json с сайта погоды.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCwithWebAPI.Models
{
    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; }
    }
    public class Coord
    {
        public double lon { get; set; }
        public double lat { get; set; }
    }

    public class Weather
    {
        public int id { get; set; }
        public string main { get; set; }
        public string description { get; set; }
        public string icon { get; set; }
    }

    public class Main
    {
        public double temp { get; set; }
        public int pressure { get; set; }
        public int humidity { get; set; }
        public double temp_min { get; set; }
        public double temp_max { get; set; }
    }

    public class Wind
    {
        public double speed { get; set; }
        public int deg { get; set; }
    }

    public class Clouds
    {
        public int all { get; set; }
    }

    public class Sys
    {
        public int type { get; set; }
        public int id { get; set; }
        public string country { get; set; }
        public int sunrise { get; set; }
        public int sunset { get; set; }
    }


}


Это контроллер

namespace MVCwithWebAPI.Controllers
{
    public class WeatherController : Controller
    {
        readonly string apiBaseAddress = ConfigurationManager.AppSettings["apiBaseAddress"];
        // GET: Weather

        public async Task<ActionResult> Index(string city)
        {

            using (var client = new HttpClient())
            {
                try
                {
                    city = "Karachi";
                    client.BaseAddress = new Uri("http://api.openweathermap.org");
                    var response = await client.GetAsync($"/data/2.5/weather?q={city}&appid=ef7f1c41e192cb1d2a2800d17ad9388f");
                    response.EnsureSuccessStatusCode();

                    var stringResult = await response.Content.ReadAsStringAsync();
                    var weatherResponseModel = JsonConvert.DeserializeObject<RootObject>(stringResult);

                    return View(weatherResponseModel);

                }
                catch (HttpRequestException httpRequestException)
                {

                    throw new Exception(httpRequestException.ToString());
                }
            }

            return View();
        }
}

Модель была создана Json, которая была возвращена с сайта API погоды. "WeatherResponseModel"

{
    "coord": {
        "lon": 67.03,
        "lat": 24.87
    },
    "weather": [
        {
            "id": 800,
            "main": "Clear",
            "description": "clear sky",
            "icon": "01d"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 308.15,
        "pressure": 1010,
        "humidity": 20,
        "temp_min": 308.15,
        "temp_max": 308.15
    },
    "visibility": 7000,
    "wind": {
        "speed": 3.47,
        "deg": 206
    },
    "clouds": {
        "all": 0
    },
    "dt": 1571902234,
    "sys": {
        "type": 1,
        "id": 7576,
        "country": "PK",
        "sunrise": 1571880844,
        "sunset": 1571921876
    },
    "timezone": 18000,
    "id": 1174872,
    "name": "Karachi",
    "cod": 200
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...