Saket Choubey
Saket Choubey

Reputation: 916

How to bind key value pair to dropdown in MVC4 Razor

I have country table "tblCountry", Where there is 2 columns country name, Country ID, I want to display country name but store country id in rest of the tables. Please tell me the approach from creating models to view, I am using database first approach.

public partial class tblRFATCountry
{
    public long CountryID { get; set; }
    public string Country { get; set; }
}

This is my model where i tried to add a dictionary.

public partial class tblRFATCountry
{
    public long CountryID { get; set; }
    public string Country { get; set; }
    public dictionary<string, long> countryDic = new dictionary<string, long>();
} 

I want to do something like that so that i can display name but store value. Please suggest

Upvotes: 2

Views: 9286

Answers (3)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

you need to do something like :

@{

    Dictionary<long, string> dictionaryCountry = new Dictionary<long, string>()
    {
      {1, "Item1"},
      {2, "Item2"},
      {3, "Item3"},
      {4, "Item4"},
    };



     SelectList countryList= new SelectList(
            dictionaryCountry.Select(x => new { Value = x.Key, Text = x.Value }),
            "Value",
            "Text"
        );

}

@Html.DropDownList("DDLCounry", countryList)

you can refer here for more details

Upvotes: 5

invernomuto
invernomuto

Reputation: 10211

With the help of an utility class you can do something like this

C# Utility Class

using System.Collections.Generic;using System.Web.Mvc;

namespace YourNameSpace.Domain.Utilities
{
    public static class DropDownList<T>
    {
        public static SelectList LoadItems(IList<T> collection, string value, string text)
        {
            return new SelectList(collection, value, text);
        }
    }

}

Controller

ViewBag.CountryList = Domain.Utilities.DropDownList<tblRFATCountry>.LoadItems(YourRepository.Countries.ToList(), 
"CityID", "CityName");

View

@Html.DropDownListFor(model => model.CountryID, (IEnumerable<SelectListItem>)ViewBag.CountryList, "--Select--", new { @class = "select" })

Upvotes: 1

3dd
3dd

Reputation: 2530

The dropdown list can be implemented as follows

@Html.DropDownListFor(m => m.SelectedCountryId, new SelectList(Model.Countries, "CountryID", "Country"), "Please select a country")

The ViewModel would then need the following properties

public long SelectedCountryId {get; set;}
public List<tblRFATCountry> Countries {get; set;} 

Upvotes: 4

Related Questions