rikket
rikket

Reputation: 2407

MVC populating drop down list from database

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 Model:

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

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);
    }

Currency Repository:

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

        return query.ToList();
    }

Error I am getting:

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]'.

Thanks!

Upvotes: 0

Views: 4549

Answers (2)

emre nevayeshirazi
emre nevayeshirazi

Reputation: 19241

Your view expects a strongly typed model of type

IEnumerable<DSABankSolution.Models.ExchangeRates>

However,you are passing

IEnumerable<CommonLayer.Currency> 

back to view.

Upvotes: 0

von v.
von v.

Reputation: 17108

The error says it all. You are returning a collection of Currency as shown by this code

IEnumerable<CommonLayer.Currency> currency

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>

or return a list of ExchangeRates from your controller method

Upvotes: 1

Related Questions