Suraj Kumar
Suraj Kumar

Reputation: 5643

How to set default value "0" to text "Select" in DropDownList in MVC?

Below is the dropdownlist of Country. I want selected text "Select" which is working.

@Html.DropDownList("ddlCountryName", 
 new SelectList(ViewBag.CountryName, "CountryId", "CountryName"), 
 new { @class = "form-control" })

Now I want to set the value "0" for text "Select" which is by default selected. Currently the value for "Select" is blank as shown below.

enter image description here

How can I do this? The value "Select" is not in the data source. I have to access this selected value in JQuery.

I have tried with these two but none of those are working.

@Html.DropDownList("ddlCountryName", 
new SelectList(ViewBag.CountryName, "CountryId", "CountryName"),
"Select", new { @class = "form-control", @selected = "0" })

And

@Html.DropDownList("ddlCountryName", 
new SelectList(ViewBag.CountryName, "CountryId", "CountryName"),
"Select", new { @class = "form-control", @selected = "0" })

Below is the controller code for CountryName values

ViewBag.CountryName = dbLMS.CountryMasters.Select(c => new { c.CountryId, c.CountryName }).OrderBy(c => c.CountryName).ToList();

Upvotes: 0

Views: 1526

Answers (3)

TanvirArjel
TanvirArjel

Reputation: 32069

You can do as follows:

Option-1:

@{
  var countrySelectList =  new SelectList(ViewBag.CountryName, "CountryId", "CountryName");

  List<SelectListItem> countrySelectListItems  = countrySelectList.ToList();
  countrySelectListItems.Insert(0, (new SelectListItem { Text = "Please select", Value = "0", Selected = true }));
}

@Html.DropDownList("ddlCountryName", countrySelectListItems , new { @class = "form-control" })

Option-2:

In the controller method:

List<SelectListItem> selectListItems = dbLMS.CountryMasters.Select(a => new SelectListItem()
{
    Text = a.CountryName,
    Value = a.CountryId
}).ToList();

selectListItems.Insert(0, new SelectListItem(){Text = "Selet Country", Value = "0", Selected = true});
ViewBag.CountrySelectList = selectListItems;

Then in the view:

@Html.DropDownList("ddlCountryName", (List<SelectListItem>)ViewBag.CountrySelectList, new { @class = "form-control" })

Upvotes: 4

Gauravsa
Gauravsa

Reputation: 6524

You dont really need a value for Select. For the model, keep the Required validation attribute.

This will ensure the value is selected. This way you dont have to check in the backend.

Upvotes: 0

JamesS
JamesS

Reputation: 2300

new SelectList(ViewBag.CountryName, "CountryId", "CountryName", //Default value)

Upvotes: 1

Related Questions