我看到了几个关于这个问题的问题,但对我来说没有人清楚。我有这个:
Currencies.cs
@($glob)
WebAPIController.cs
public class Currencies
{
public WorldCurrencies.CurrencyTypes Get()
{
var url = "http://openexchangerates.org/api/currencies.json";
var currencies = _download_serialized_json_data<CurrencyTypes>(url);
return currencies;
}
private static T _download_serialized_json_data<T>(string url) where T : new()
{
using (var w = new WebClient())
{
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
var res = !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
return res;
}
}
}
和Index.cshtml
public class WebAPIController : Controller
{
public ActionResult Converter()
{
WorldCurrencies.Currencies curr = new WorldCurrencies.Currencies();
return View("Index", curr.Get());
}
}
我正在尝试使用名为currency的对象填充DropDownList,但我不清楚如何实现它。
任何线索?
编辑:这正是curr.Get()返回的内容:
<div class="form-group">
<label for="fromC">From Currency</label>
<div class="col-md-6">
@Html.DropDownList("Prueba", Model, )
</div>
</div>
答案 0 :(得分:1)
让我们一次性做一件事。
您的数据格式是什么?
这是一个像这样的对象:
{
"AED": "United Arab Emirates Dirham",
"AFN": "Afghan Afghani",
"ALL": "Albanian Lek",
"AMD": "Armenian Dram",
"ANG": "Netherlands Antillean Guilder"
}
所以我们有一个包含键/值对的包,关键是货币的代码,值是货币的名称。
我们如何反序列化?
简单如下:
var res = JsonConvert.Deserialize<Dictionary<string,string>>(json_data);
我们想在视图中显示什么?
至少包含所有可用货币的下拉菜单。如果需要显示更多数据,则必须在模型中添加额外属性,并在创建模型时相应地初始化它们。
我们如何实现这一目标?
@model CurrencyModel
<div class="form-group">
<label for="fromC">From Currency</label>
<div class="col-md-6">
@Html.DropDownList("Currencies", CurrencyModel.Currencies)
</div>
</div>
我们需要什么?
至少有一个名为IEnumerable<SelectListItem>
Currencies
的属性的模型,名为public class CurrencyModel
{
public IEnumerable<SelectListItem> Currencies { get; set; }
}
:
public class WebAPIController : Controller
{
public ActionResult Converter()
{
var currencies = new CurrenciesRepository.GetAll();
var currencyModel = new CurrencyModel
{
Currencies =
currencies.Select(currency => new SelectListItem {
Text = currency.Value,
Value = currency.Key});
}
return View("Index", currencyModel);
}
}
谁将创建此模型?
此责任属于控制人。
CurrenciesRepository
现在需要的是是创建一个新类public class CurrenciesRepository
{
string _url = "http://openexchangerates.org/api/currencies.json";
public IDictionary<string, string> GetAll()
{
using (var webClient = new WebClient())
{
var data = webClient.DownloadString(_url);
var currencies= JsonConvert.DeserializeObject<Dictionary<string,string>>(data);
return currencies;
}
}
}
check_output