Md Ghouse Md Ghouse - 3 years ago 201
C# Question

How can I bind CountryNames in DropDownListFor

I'm using mvc4. How can I Bind CuntryName and its values in DropdownList
Country?

public class Country
{
public int Cnt_Id { get; set; }
public string Cnt_Name { get; set; }
}


This is my private class

public class HybridEmployee
{
public IEnumerable<Country> GetCount { get; set; }
}


Controller

public ActionResult GetCountry()
{
var x = ObjRepo.GetCountry();
hybrid.GetCount = x;
return View(hybrid);
}


Index.cshtml

@model Mvc_Application.Models.HybridEmployee
@using Mvc_Application.Models
@using (Html.BeginForm("SaveEmp", "Home", FormMethod.Post))
{
@Html.DropDownListFor(x=>x.GetCount.FirstOrDefault().Cnt_Id),new SelectList(Model.GetCount,"","");
}

Answer Source

We can have two approaches as shown below:

  1. Using a ViewBag containing the data for dropdown list.

Model file:

public class State
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public int CountryID { get; set; }
}

In .cs file:

ViewBag.Countries = countryService.All().Select(x => new SelectListItem() { Text = x.Name, Value = x.Id.ToString() }).ToList();

In .cshtml file:

@Html.DropDownListFor(x => x.CountryID, ViewBag.Countries as IEnumerable<SelectListItem>, "Select Country", new { @class = "form-control" })
  1. Using a Model's property containing the data for dropdown list.

Model file:

public class State
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public int CountryID { get; set; }

    public List<SelectListItem> Countries { get; set; }
}

In .cs file:

model.Countries = countryService.All().Select(x => new SelectListItem() { Text = x.Name, Value = x.Id.ToString() }).ToList();

In .cshtml file:

@Html.DropDownListFor(x => x.CountryID, Model.Countries, "Select Country", new { @class = "form-control" })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download