MVC从数据库填充下拉列表
我对MVC来说还很陌生.我试图用从数据库中检索的货币填充下拉列表.我在做什么错了?
Im pretty new to MVC. Im trying to populate a drop downlist with currencies retrieved from database. What am I doing wrong?
@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模型:
ExchangeRate Model:
public class ExchangeRates
{
public string ID { get; set; }
public string Name { get; set; }
}
ExchangeRate控制器:
ExchangeRate Controller:
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]'.
The model item passed into the dictionary is of type 'System.Collections.Generic.List
1[CommonLayer.Currency]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
1[DSABankSolution.Models.ExchangeRates]'.
谢谢!
错误说明了一切.您将返回Currency
的集合,如该代码所示
The error says it all. You are returning a collection of Currency
as shown by this code
IEnumerable<CommonLayer.Currency> currency
,但是您的视图期望为ExchangeRates
and yet your view expect as a collection of ExchangeRates
@model IEnumerable<DSABankSolution.Models.ExchangeRates>
因此您可以将视图中的声明更改为
so you either change the declaration in your view to
@model IEnumerable<CommonLayer.Currency>
或通过控制器方法返回ExchangeRates
的列表
or return a list of ExchangeRates
from your controller method