I am generating a drop down list for languages. I want to make a specific item of that list as selected. Here is the view page code:
#{var languageList = new List<SelectListItem>();
var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
foreach (var culture in cultures)
{
if(culture.NativeName != "Invariant Language (Invariant Country)")
{
languageList.Add(new SelectListItem {
Text = (culture.EnglishName != culture.NativeName) ?
culture.EnglishName + " - " + culture.NativeName :
culture.EnglishName,
Value = culture.EnglishName.Contains('(') ?
culture.EnglishName.Split('(')[0].ToString().Trim() :
culture.EnglishName
});
}
}
languageList.OrderBy(x => x.Value);
}
Now if I call that list like this:
#Html.DropDownListFor(m => m.Language, languageList, "English", new { #class = "form-control" })
Then it will not select the English value. It will simple create a new text English with value null and set it to the top of the list. This is good when we want to use something like --Select Item--. But I want to make that specific item selected whose value is English and text is English (United States). How do I do it?
languageList.Add(new SelectListItem
{
Text = (culture.EnglishName != culture.NativeName) ?
culture.EnglishName + " - " + culture.NativeName : culture.EnglishName,
Value = culture.EnglishName.Contains('(') ?culture.EnglishName.Split('(')0].ToString().Trim() : culture.EnglishName,
Selected = (culture.EnglishName == "English (United States)") ? true : false
});
You can use derloopkat's solution also.
Set the selected item when populating the list:
var defaultListItem = new SelectListItem()
{
Text = "English (United States)",
Value = "English",
Selected = true
};
languageList.Add(defaultListItem);
So you don't need to specify selected in Html helper.
#Html.DropDownListFor(m => m.Language, languageList, new { #class = "form-control" })
This generates an option that looks like:
<option selected="selected" value="English">English (United States)</option>
You are currently using the wrong overload of DropDownListFor, the "English" you are setting is for the default value if empty not the selected value. One way to resolve this issue would be to set the value in the SelectList:
#Html.DropDownListFor(m => m.Language, new SelectList(languageList, "Value", "Text", "English") ,new { #class = "form-control" })
Although this could result in any of the items with value "English" being selected.
Related
In the controller Index I have the following:
ViewBag.Assignees = (await GetAllUsers()).Select(a =>
new SelectListItem
{
Text = a.DisplayName,
Value = a.Username,
Selected = a.DisplayName == "John Smith"
}).OrderBy(x => x.Text).ToList();
In the View, I have the following:
#Html.DropDownListFor(model => model.Assignee,
ViewBag.Assignees as List<SelectListItem>,
"Select Assignee",
new { id = "ddlAssignee", #class = "form-control"})
The dropdownlist populates as expected, however, the default (selected = true) value, which does exist, does not get set. Can someone advise what is wrong in the above?
UPDATE:
By Changing the SelectListItem.Value to a.DisplayName (same as SelectedListItem.Text) I achieved it. Still not sure what prevents the dropdownlist from displaying the item with Selected = true
If the model.Assignee comes with value, and if it is an int it will be defaulted to 0, it will override the SelectListItem selected value.
I suggest to set up the model.Assignee.
Here two ways that i use.
WAY 1
#Html.DropDownListFor(model => model.Assignee,
ViewBag.Assignees as List<SelectListItem>,
"Value", // property to be set as Value of dropdown item
"Text", // property to be used as text of dropdown item
"1"), // value that should be set selected of dropdown
new { id = "ddlAssignee", #class = "form-control"})
WAY 2
<select name="SelectName" value="1" class="w-100">
#foreach (var item in ViewBag.Collection) {
<option value="#item.Id">#item.Name</option>
}
</select>
I hope it work for you
#Html.DropDownListFor how to set default value
In your view set:
#Html.DropDownListFor(model => model.Assignee,
ViewBag.Assignees as List<SelectListItem>,
"Select Assignee",
new { id = "ddlAssignee", #class = "form-control", #value = "Default value"})
When you have list already defined.
Use This
#Html.DropDownList("CoverageDropDown", new SelectList(Model.youList, "Code", "Description",item.seletecItem), "Select")
I have the below code that I use to populate my dropdown in my Razor Page
I want to preselect a description - the "Value" of that needs to be set is found in
s.UserEstablishmentId
How can I preselect this on the dropdown
#Html.DropDownList("drpEstablishments",
getEstablishments().Select(s => new SelectListItem()
{
Text = s.Description,
Value = s.EstablishId.ToString()
}),
new
{
#class = "dropdown form-control"
})
You're using linq to create a new SelectListItem for getEstablishments element. When creating each instance of a SelectListItem() you need to determine if Selected should be true or false. Simply replace YourConditionForSelectionHere with a method that returns a bool or syntax that returns a bool, shown below:
#Html.DropDownList("drpEstablishments",
getEstablishments().Select(s => new SelectListItem()
{
Selected = (YourConditionForSelectionHere),
Text = s.Description,
Value = s.EstablishId.ToString()
}),
new
{
#class = "dropdown form-control"
})
in the end something like this worked
Selected= (s.UserEstablishmentId==s.EstablishId)? true:false,
I want to set a local variable as selected in a dropdownlist but it is not working for me.
Here my code :
#{
List
<SelectListItem>
dateEcheancier = new List
<SelectListItem>
();
foreach (var dateEch in arrayDateEcheancier)
{
dateEcheancier.Add(new SelectListItem() { Text = dateEch, Value = dateEch });
}
<div id="md-select-forcage" class="md-select px-0" style="min-width:0px">
#Html.DropDownList("DateEche", new SelectList(dateEcheancier, "Value", "Text", (Selected .ToString())), new { #class = "form-conrol" })
</div>
}
And selected value it is a local variable in my code :
string Selected = ech.Value[i];
Selected = arrayMontantsIds[0];
Note that when i add a selected value like this "20/01/2019" a date in my select list it is working so how i solve this problem
You can use ViewBag
in your controller, set the value as below
ViewBag.Selected=arrayMontantsIds[0];
in your view
<div id="md-select-forcage" class="md-select px-0" style="min-width:0px">
#Html.DropDownList("DateEche", new SelectList(dateEcheancier, "Value", "Text",ViewBag.Selected) , new { #class = "form-conrol" })
</div>
I'm having this dropDownListFor:
#Html.DropDownListFor(m => m.ChoosenThemeSetting, Model.ThemeSettings.Select(k => new SelectListItem { Text = k.ChoosenTheme, Value = k.ChoosenTheme, }), "-- Select here --", new { #class = "form-control", id = "colorIfZero" })
In the code I've set "-- Select here --" as the default value. If I don't select anything else than the detault value in my dropDown, the default value will be posted to my [httpPost]-method.
Is there some way to valite this. Like: if selected value is my default value, give me a validation message to choose somthing from my dropDown. Becaues my default "-- Select here --" I would not like to send to my [httpPost]
Problem solved thank's to this link: http://forums.asp.net/t/1580133.aspx?DropDownListFor+validation. Thank you ravikatha!
By setting the model-class that hold the property for ChoosenThemeSetting to (in the class)
[Required]
[DisplayName("")]
public string ChoosenThemeSetting { get; set; }
And then change my DropDown-code to this (note the string.empty-line)
#Html.DropDownListFor(m => m.ChoosenThemeSetting, Model.ThemeSettings.Select(k => new SelectListItem { Text = k.ChoosenTheme, Value = k.ChoosenTheme, }), string.Empty, new { #class = "form-control", id = "colorIfZero" })
And everything works fine!
I now get a validationmessage to chose some of the values from my DropDown
I have gone through numerous methods of trying to set the value of a dropdownlist and must be doing something silly because none of the methods are working.
#Html.DropDownList("startTime", #Model.startTimeList, new { #class = "startTime", style = "width: 100px;" })
Its a generated list of half hour increments.
In my controller I set this string value..
model.startTime = myTime + " " + amOrPm; //ex 10:30 PM
My List looks like this.
List<SelectListItem> startTimeList = new List<SelectListItem>();
SelectListItem time12 = new SelectListItem { Text = "12:00 PM", Selected = false, Value = "12:00PM" };
startTimeList.Add(time12);
SelectListItem time12Half = new SelectListItem { Text = "12:30 PM", Selected = false, Value = "12:30PM" };
startTimeList.Add(time12Half);
My list always defaults to 12:00 PM because its the first one entered into the list. I want that if model.startTime has a value it sets to that value.
You can use DropDownListFor and let the Razor engine do the work of selecting the item that matches the property.
#Html.DropDownListFor(model => model.startTime, startTimeList)
The alternative would be to explicitly set Selected on the item that matches:
startTimeList.First(item => item.Text.Equals(model.startTime)).Selected = true;
If you have a startTime property on your model, and the value of that property matches one of the values in the list (ie, it matches "12:00PM", or "12:30PM" but not "12:00 PM" or "12:30 PM"), then I think this should work:
#Html.DropDownListFor(model => model.startTime,
#Model.startTimeList,
new { #class = "startTime", style = "width: 100px;" })