MVC从数据库填充下拉列表

时间:2013-05-07 11:12:20

标签: asp.net-mvc razor html-select

我对MVC很新。我试图用从数据库中检索的货币填充下拉列表。我做错了什么?

@model IEnumerable<DSABankSolution.Models.ExchangeRates>

@{
    ViewBag.Title = "Exchange Rates";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<br /> <br /> 


     <input type="text" size="5" value="1" />
        @Html.DropDownList("currency", Model.Select(p => new SelectListItem{ Text = p.Name, Value = p.ID})) 
        to  
       @Html.DropDownList("currency", Model.Select(p => new SelectListItem { Text = p.Name, Value = p.ID }));
    <br /> <br /> <input type="submit" name="Convert" />

ExchangeRate模型:

public class ExchangeRates
{
    public string ID { get; set; }
    public string Name { get; set; }
}

ExchangeRate控制器:

 public ActionResult Index()
    {
        IEnumerable<CommonLayer.Currency> currency = CurrencyRepository.Instance.getAllCurrencies().ToList();
        //ViewBag.CurrencyID = new SelectList(currency, "ID");
        //ViewBag.Currency = new SelectList(currency, "Name");

        return View(currency);
    }

货币存储库:

public List<CommonLayer.Currency> getAllCurrencies()
    {
        var query = from curr
                    in this.Entity.Currencies
                    select curr;

        return query.ToList();
    }

我收到错误:

  

传递到字典中的模型项是类型的   'System.Collections.Generic.List 1[CommonLayer.Currency]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1 [DSABankSolution.Models.ExchangeRates]'。

谢谢!

2 个答案:

答案 0 :(得分:1)

错误说明了一切。您将返回Currency的集合,如此代码所示

IEnumerable<CommonLayer.Currency> currency

但您的观点期望为ExchangeRates

的集合
@model IEnumerable<DSABankSolution.Models.ExchangeRates>

因此您要么将视图中的声明更改为

@model IEnumerable<CommonLayer.Currency>

或从控制器方法

返回ExchangeRates列表

答案 1 :(得分:0)

您的视图需要类型为

的强类型模型
IEnumerable<DSABankSolution.Models.ExchangeRates>

但是,你正在传递

IEnumerable<CommonLayer.Currency> 

回到视野。