【问题标题】:Populate Razor DropDownList with Object passed from Controller C#使用从控制器 C# 传递的对象填充 Razor DropDownList
【发布时间】:2015-09-25 19:14:40
【问题描述】:

我看到了一些关于这个东西的问题,但没有一个对我来说很清楚。我有这个:

Currencies.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;
        }
    }
}

WebAPIController.cs

public class WebAPIController : Controller
{
    public ActionResult Converter()
    {
        WorldCurrencies.Currencies curr = new WorldCurrencies.Currencies();

        return View("Index", curr.Get());
    }
}

还有Index.cshtml

<div class="form-group">
    <label for="fromC">From Currency</label>
    <div class="col-md-6">
        @Html.DropDownList("Prueba", Model, )
    </div>
</div>

我正在尝试使用名为 currency 的对象填充 DropDownList,但我不清楚如何实现这一点。

有什么线索吗?

编辑:这正是 curr.Get() 返回的内容:

    res {WorldCurrencies.CurrencyTypes} WorldCurrencies.CurrencyTypes
    AED "United Arab Emirates Dirham"   string
    AFN "Afghan Afghani"    string
    ALL "Albanian Lek"  string
    AMD "Armenian Dram" string
    ANG "Netherlands Antillean Guilder" string
    AOA "Angolan Kwanza"    string
    ARS "Argentine Peso"    string
    AUD "Australian Dollar" string
    AWG "Aruban Florin" string
    AZN "Azerbaijani Manat" string
    BAM "Bosnia-Herzegovina Convertible Mark"   string
    BBD "Barbadian Dollar"  string
    BDT "Bangladeshi Taka"  string
    BGN "Bulgarian Lev" string
    ...

【问题讨论】:

  • 您尝试过哪些失败的事情? DropDownList 方法非常简单。
  • @Html.DropDownList("Prueba", Model, ) ?
  • 我认为 curr.Get() 没有返回相当于 IEnumerable selectList

标签: c# asp.net .net asp.net-mvc razor


【解决方案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&lt;SelectListItem&gt; 的属性称为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;
        }
    }
}

【讨论】:

  • 我需要给您送一杯啤酒或其他东西来感谢您。所以,再次感谢您对假人的解释。我不得不在我的工作场所用一个月的时间学习 C#,现在很难实现所有东西......非常感谢老兄。
  • @Tincho.UY 不客气!我很高兴能帮上忙:)
猜你喜欢
  • 2019-12-12
  • 2013-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多