1
votes

how do I display the text value(CountryName) from the selected id (CountryId) in a SelectList? The SelectList is contained in a view model sent to Details view template. The field is currently displaying CountryID. I want CountryName.

view

<div class="display-field">@Model.Dinner.CountryID</div>

controller

public ActionResult Details(int id)
    {
        Dinner dinner = dinnerRepository.GetDinner(id);
        DinnerFormViewModel model = new DinnerFormViewModel(dinner);
        if (dinner == null)   
            return View("NotFound");       
        else           
            return View("Details", model);
    }

viewmodel

public class DinnerFormViewModel
{
    public Dinner Dinner { get; private set; }
    public SelectList CountriesList { get; private set; }

    public DinnerFormViewModel(Dinner dinner)
    {
        Dinner = dinner;

        var items = new List<Country>() {
                new Country() { 
                    CountryID = 1,
                    CountryName = "England"
                },
                new Country() { 
                    CountryID = 2,
                    CountryName = "Ireland"
                },
                new Country() { 
                    CountryID = 3,
                    CountryName = "Scotland"
                },
                new Country() { 
                    CountryID = 3,
                    CountryName = "Wales"
                }
            };

        CountriesList = new SelectList(items, "CountryID", "CountryName", 2);
    }
}

Again this is just to display the CountryName value in a label. Dont want to edit it or anything. LINQ expression?

2

2 Answers

2
votes

This works great

<div class="display-label">Country</div>
<div class="display-field">@Html.Encode(Model.CountriesList.SingleOrDefault(c => int.Parse(c.Value) == Model.Dinner.CountryID).Text)</div>

With thanks to related post.

1
votes

I would create a new class to help with lookups. In my example code the class is "BusinessResources" In that class I would create a method for each lookup like the one depicted below for country. A Dictionary is perfect for what you're trying to accomplish.

public static Dictionary<string, string> GetCountryList()
        {
            Dictionary<string, string> country = new Dictionary<string, string>();

            Capture2Entities db = new Capture2Entities();
            country = db.CountryLists.Where(x => x.IsDisabled == false)
                                 .OrderBy(x => x.CountryName)
                                 .Select(x => new { x.ID_Country, x.CountryName })
                                 .ToDictionary(key => key.ID_Country.ToString(), val => val.CountryName);
            return country;
        }

View would look like this

<div class="display-label">@Html.LabelFor(model => model.ID_Country)</div>
<div class="display-field">@Html.DropDownListFor(model => model.ID_Country, new SelectList(BusinessResources.GetCountryList(),"Key","Value"))</div>