Setting default value to Html.DropDownListFor

14,438

Solution 1

If you want to pass default value for the dropdown list than you can do is pass default viewmodel/model with default value

Example :

public ActionResult New()
{
    MyViewModel myViewModel = new MyViewModel ();
    myViewModel.OfficeAddressCountry = default value; 
    //Pass it to the view using the `ActionResult`
    return ActionResult( myViewModel);
}

or you can try this

 var list = new SelectList(Db.Countries, "CountryCode", "CountryName")
 list.Add(new SelectListItem(){Value = 1,Text = "Deafult Item",Selected = true };)
 ViewBag.ListOfCountries = list;

Solution 2

You have to use different overlaod of DropDownListFor. Consider this:

<%: Html.DropDownListFor(m => m.OfficeAddressCountry,
                         ViewBag.ListOfCountries as SelectList,
                         "Default Selected Option",
                         new{@class="required"}) %>

Now it will set default selected option to "Default Selected Option" if the model property OfficeAddressCountry contains no value.

You can check this fiddle for default value and this with selected option which is in Model

Share:
14,438
Rajan Goswami
Author by

Rajan Goswami

Hi, I am a software developer by profession. I have two years of experience of working with ASP.net, MVC, Javascript, Bootstrap, CSS3.

Updated on June 04, 2022

Comments

  • Rajan Goswami
    Rajan Goswami almost 2 years

    I am populating a dropdownlist in mvc using viewbag. i want to set a default value to this dropdownlist, if the page is not saved with any other value. Otherwise the selected item should be the one they select and save the page.

    this is how i populate my viewbag

    ViewBag.ListOfCountries = new SelectList(Db.Countries, "CountryCode", "CountryName");
    

    this is the view side:

    <%: Html.DropDownListFor(m => m.OfficeAddressCountry, (IEnumerable<SelectListItem>)ViewBag.ListOfCountries, new{@class="required"}) %>
    
  • Krishna
    Krishna almost 9 years
    myViewModel.OfficeAddressCountry ==null?default value: myViewModel.OfficeAddressCountry;
  • Krishna
    Krishna almost 9 years
    Should it not be default only when the user has not selected an option?
  • Krishna
    Krishna almost 9 years
    you could use Pranay's solution with an IFF clause on default value as in my comment. should work I believe
  • Pranay Rana
    Pranay Rana almost 9 years
    @Krishna - I am assumething that it called new action here ...if use selcted and submit it calls post action so this just kind of intialization when new get called for creating new record ..later task handle by post method of new
  • Krishna
    Krishna almost 9 years
    sorry missed the New() -
  • Ehsan Sajjad
    Ehsan Sajjad almost 9 years
    in default case we can enter null or -1 in database