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.
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();
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" })