Setting Selected Value of DropDownList in MVC 3 - c#

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

Related

How to set default value for ASP.NET MVC DropDownList from ViewBag

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")

preselect dropdown list razor page

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,

How can I get a SelectListItem other than the one with value=0 to be selected by default?

I have a <select> for weekdays in a ViewComponent Default.cshtml, each day with the associated values of 0-6 (Sunday to Saturday). However, I want Monday to be listed as the first day, so in my ViewModel, I have this:
public List<SelectListItem> SelectableWeekdays => new List<SelectListItem>
{
new SelectListItem { Text = "Monday", Value = "1", Selected = true },
new SelectListItem { Text = "Tuesday", Value = "2", Selected = false },
new SelectListItem { Text = "Wednesday", Value = "3", Selected = false },
new SelectListItem { Text = "Thursday", Value = "4", Selected = false },
new SelectListItem { Text = "Friday", Value = "5", Selected = false },
new SelectListItem { Text = "Saturday", Value = "6", Selected = false },
new SelectListItem { Text = "Sunday", Value = "0", Selected = false }
};
In my view, I'm rendering the dropdown like this:
<select asp-for="Weekday" class="form-control" asp-items="#Model.SelectableWeekdays">
</select>
I have also tried adding a selected, disabled option manually:
<select asp-for="Weekday" class="form-control" asp-items="#Model.SelectableWeekdays">
<option selected disabled>Please choose</option>
</select>
No matter what I have been trying, the selected option is always "Sunday" with the attribute selected="selected" being set for that day.
I have also tried adding
new SelectListItem { Text = "Please choose", Value = "99", Selected = true, Disabled = true },
in the ViewModel, and omitting the manual option in my view, but that didn't work either. The disabled "Please choose"-option was there at the top of the list, but Sunday was still the selected option.
I believe the issue is the value of the underlying model's property Weekday.
If you set the value of this property to the option you want selected by default (1 in this case), the control will be rendered accordingly.

DropDownListFor pick an item and make it selected

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.

SelectList not selecting a default value from List<string>

I am starting to get very annoyed with this, but no matter what, I am not able to get SelectedValue to work for a SelectList.
This is my code:
List<string> PickupTimeList = EntityLogic.PopulateTimeSlots(vm.DateMileage.PickupDate,
vm.DateMileage.PickupDate.AddHours(-2), vm.DateMileage.PickupDate.AddHours(2).AddMinutes(15));
ViewBag.PickupTimeList = new SelectList(PickupTimeList, "11:00 PM");
I don't have a Text/Key value here because Text/Key will also be a string and same thing. Anyway, by this code, it's still not selecting "11:00 PM" as the default item.
What can I do to fix this problem?
Try like this:
var pickupTimeList = EntityLogic.PopulateTimeSlots(
vm.DateMileage.PickupDate,
vm.DateMileage.PickupDate.AddHours(-2),
vm.DateMileage.PickupDate.AddHours(2).AddMinutes(15)
)
.Select(x => new SelectListItem
{
Value = x,
Text = x,
});
ViewBag.PickupTimeList = new SelectList(PickupTimeList, "Value", "Text", "11:00 PM");

Categories

Resources