MVC从数据库填充下拉列表 [英] MVC populating drop down list from database

查看:81
本文介绍了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.List1[CommonLayer.Currency]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[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

这篇关于MVC从数据库填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆