preselect dropdown list razor page - c#

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,

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

set a local variable as selected value

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>

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.

Choosing selected item for dropdown list in action

I have a page which allows users to change their privacy settings for:
Their posted recipes
Their profile
Their posted lists
I am trying to form my code so that when the users load this page, the dropdown lists which they use to select their privacy settings display their current setting, so if they had their recipe privacy set to "Registered users", whenever they load the privacy settings page I want it to start off with "Registered users" selected.
Initially I create a list of SelectListItem instances called PrivacySettings
List<SelectListItem> PrivacySettings = new List<SelectListItem>();
PrivacySettings.Add(
new SelectListItem
{
Text="Anybody",
Value = "0"
});
PrivacySettings.Add(
new SelectListItem
{
Text = "Registered users",
Value = "1"
});
PrivacySettings.Add(
new SelectListItem
{
Text = "Only me",
Value = "2"
});
Then I create three separate SelectList instances. Here is the part where I am assigning the selected value for each of the lists to the first value which matches the user's saved setting.
SelectList RecipePrivacyList = new SelectList(
PrivacySettings,
"Value",
"Text",
PrivacySettings.First(x => x.Value == LoggedInUser.RecipePrivacy.ToString()));
SelectList ProfilePrivacyList = new SelectList(
PrivacySettings,
"Value",
"Text",
PrivacySettings.First(x => x.Value == LoggedInUserProfile.Privacy.ToString()));
SelectList ListPrivacyList = new SelectList(
PrivacySettings,
"Value",
"Text",
PrivacySettings.First(x => x.Value == LoggedInUser.ListPrivacy.ToString()));
Then I assign each of these to separate ViewData keys
ViewData["RecipePrivacy"] = RecipePrivacyList;
ViewData["ProfilePrivacy"] = ProfilePrivacyList;
ViewData["ListPrivacy"] = ListPrivacyList;
In my view I retrieve these and store them into variables
var ProfilePrivacy = (SelectList)ViewBag.ProfilePrivacy;
var RecipePrivacy = (SelectList)ViewBag.RecipePrivacy;
var ListPrivacy = (SelectList)ViewBag.ListPrivacy;
And finally I use the Html.DropDownList() helper method to create the lists using the aforementioned variables
#Html.DropDownList("profile-privacy", ProfilePrivacy, new { #class = "profile-privacy" })
When the view is loaded, the first value ("Anyone" or value 0) is selected regardless of the user's actual setting.
you have to set the selected item of the SelectList like that:
SelectList ListPrivacyList = new SelectList(
PrivacySettings,
"Value",
"Text",
PrivacySettings.First(x => x.Value == LoggedInUser.ListPrivacy.ToString()).Value);

MVC DropDownListFor - SelectedItem not working for nested value

In my C#, MVC4 .NET WebApplication I have a custom helper that has the following method-call:
#Custom.DropDownListFor(m => m.CategorySetups[categoryId].Gender, CategoryHelper.Genders, new { #class = "form-control" })
which is internally something like:
#Html.DropDownListFor(expression, new SelectList(items, "Value", "Text"))
because I have an override of SelectListItem here.
This call is not selecting the value in the rendered view as stored in
m.CategorySetups[categoryId].Gender
If I call the method this way (not in the same view):
#Custom.DropDownListFor(m => m.Gender, CategoryHelper.Genders, new { #class = "form-control" })
The rendered HTML has the correct value marked as
<option value="Under15" selected>Under15</option>
So my guess is, that is has something to do with nesting of the property that is selected but I don't see it.
From debugging I can see, that
m.CategorySetups[categoryId].Gender
has the correct value set when it should render the select.
Note: Not sure if this may causing the issue (because the second way it's working) but the bound values Type is Enum.
Update as of comments:
The implementation is as follows:
public static readonly List<SelectListItem<ClassificationType>> ClassificationTypes = new List<SelectListItem<ClassificationType>>
{
new SelectListItem<ClassificationType> {Text = #"please select...", Value = ClassificationType.NotSet},
new SelectListItem<ClassificationType> {Text = EnumParser.GetString(ClassificationType.Under13), Value = ClassificationType.Under13},
new SelectListItem<ClassificationType> {Text = EnumParser.GetString(ClassificationType.Under15), Value = ClassificationType.Under15},
new SelectListItem<ClassificationType> {Text = EnumParser.GetString(ClassificationType.Under18), Value = ClassificationType.Under18},
new SelectListItem<ClassificationType> {Text = EnumParser.GetString(ClassificationType.Over30), Value = ClassificationType.Over30},
new SelectListItem<ClassificationType> {Text = EnumParser.GetString(ClassificationType.Open), Value = ClassificationType.Open}
};
The SelectList contructor has an overload which takes a parameter object selectedValue, you need to specifiy the selected value, In normal DropDownListFor() we do this way:
#Html.DropDownListFor(m=>m.Gender,
new SelectList(Model.Genders,"Id","Value",Model.Gender),
new { #class = "form-control" })
UPDATED:
In your case you can do this:
#Custom.DropDownListFor(m => m.CategorySetups[categoryId].Gender,
new SelectList(CategoryHelper.Genders,"Value","Text",Model.CategorySetups[categoryId].Gender),
new { #class = "form-control" })
One thing more, as you are populating items via Enum, you can use extension method I posted in this answer

Categories

Resources