MVC - setting the selected value to SelectList

How can I set the selectedvalue property to a SelectList after it was created without the selected value,

SelectList selectList = new SelectList(items, "ID", "Name"); 

I need to set the selected value after this step

+52
c # asp.net-mvc
Sep 07 '09 at 20:17
source share
12 answers

If you have a SelectList object, just iterate over the elements in it and set the "Selected" property of the element you want.

 foreach (var item in selectList.Items) { if (item.Value == selectedValue) { item.Selected = true; break; } } 

Or with Linq:

 var selected = list.Where(x => x.Value == "selectedValue").First(); selected.Selected = true; 
+67
Sep 07 '09 at 20:35
source share

A little late for the party, but here's how simple it is:

 ViewBag.Countries = new SelectList(countries.GetCountries(), "id", "countryName", "82"); 

it uses my getcountries method to populate a model called countries, obviously you would replace it with any data source, model, etc., and then set id as the value in the select list. then just add the last parameter, in this case "82", to select the selected item by default.

[edit] Here's how to use this in Razor:

 @Html.DropDownListFor(model => model.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries, new { @class = "form-control" }) 

Important Note: In addition, one more thing to pay attention to: make sure that the model field that you use to store the selected identifier (in this case, model.CountryId) from the drop-down list is NULL and when loading the first page has null value. This one gets me every time.

Hope this saves someone time.

+22
Sep 05 '14 at 7:13
source share

Just use the third parameter for the selected value in mvc4

 @Html.DropDownList("CountryList", new SelectList(ViewBag.Countries, "Value", "Text","974")) 

"974" is selected here. The value indicated

In my answer, the selected country is now qatar.in C # as below

  foreach (CountryModel item in CountryModel.GetCountryList()) { if (item.CountryPhoneCode.Trim() != "974") { countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode }); } else { countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true }); } } 
+13
Mar 01 '16 at 8:24
source share

Why are you trying to set the value after creating the list? I assume that you are creating a list in your model, not in your view. I recommend creating a basic enumerable in your model, and then use it to create the actual SelectList:

 <%= Html.DropDownListFor(m => m.SomeValue, new SelectList(Model.ListOfValues, "Value", "Text", Model.SomeValue)) %> 

Thus, the value you choose is always set in the same way as the visualization of the view, and not earlier. In addition, you do not need to place unnecessary user interface classes (such as SelectList) in your model, and it may not know about the user interface.

+9
Jan 21 '12 at 15:34
source share

Doug answered my question ... But I will explain what my problem was and how Doug helped me solve my problem that you might run into.

I call jquery $.post and replace my div with my partial view, for example.

 function AddNewAddress (paramvalue) { $.post(url, { param: paramvalue}, function(d) { $('#myDiv').replaceWith(d); }); } 

At the same time, for some reason, when entering my model, my property associated with the selected value was never set, only until I entered the view that it fell into scope.

So, I had before

 @Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, Model.CustomerAddresses[i].YearsAtAddressSelectList, new {onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")"}) 

however, even if Model.CustomerAddresses [i] .YearsAtAddressSelectList was set ... it did not set the selected value.

So after ....

  @Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, new SelectList(Model.CustomerAddresses[i].YearsAtAddressSelectList, "Value", "Text", Model.CustomerAddresses[i].YearsAtAddress), new { onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")" }) 

and it works!

I decided not to use DropDownListFor , since it has a problem when using unobtrusive checking, so I refer to the following if your curious in a class classified

 HtmlExtensions.cs [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList) { return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, null /* htmlAttributes */); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes) { return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, new RouteValueDictionary(htmlAttributes)); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes) { return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, htmlAttributes); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel) { return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, optionLabel, null /* htmlAttributes */); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes) { return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, optionLabel, new RouteValueDictionary(htmlAttributes)); } [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Users cannot use anonymous methods with the LambdaExpression type")] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes) { if (expression == null) { throw new ArgumentNullException("expression"); } ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); IDictionary<string, object> validationAttributes = htmlHelper .GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata); if (htmlAttributes == null) htmlAttributes = validationAttributes; else htmlAttributes = htmlAttributes.Concat(validationAttributes).ToDictionary(k => k.Key, v => v.Value); return SelectExtensions.DropDownListFor(htmlHelper, expression, selectList, optionLabel, htmlAttributes); } 
+3
Apr 25 2018-12-12T00:
source share

In addition to @Womp’s answer, it’s worth noting that β€œWhere” can be dropped and the predicate can be placed directly in the β€œFirst” call, for example:

list.First(x => x.Value == "selectedValue").Selected = true;

+3
May 08 '14 at 8:24
source share

I needed a drop-down menu in an editable grid with pre-selected drop-down list values. Afaik, the selection list data is provided by the controller for presentation, so it is created before it is consumed. When a view consumes a SelectList, I pass it to a special helper, which uses the standard DropDownList helper. So a fairly easy imo solution. Guess that it fits into the spirit of ASP.Net MVC at the time of writing; when not happy with my own ...

  public static string DropDownListEx (this HtmlHelper helper, string name, SelectList selectList, object selectedValue)
 {
     return helper.DropDownList (name, new SelectList (selectList.Items, selectList.DataValueField, selectList.DataTextField, selectedValue));
 }
+2
Nov 07 '09 at 22:02
source share

You can use the method below, which is pretty simple.

 new SelectList(items, "ID", "Name",items.Select(x=> x.Id).FirstOrDefault()); 

This will automatically select the first item in your list. You can modify the above query by adding a where clause.

+1
Feb 05 '15 at 21:37
source share

I usually use this method

  public static SelectList SetSelectedValue(SelectList list, string value) { if (value != null) { var selected = list.Where(x => x.Value == value).First(); selected.Selected = true; return list; } return list; } 
+1
Sep 21 '15 at 18:12
source share

I need the dropdown menu to select the appropriate id value in the action method. The trick is to set the Selected property when creating the SelectListItem collection. It would not work otherwise, maybe I missed something, but in the end, it is more elegant of my choice.

You can write any method that returns a boolean to set the Selected value to your requirements, in my case I used the existing Equal Method

 public ActionResult History(long id) { var app = new AppLogic(); var historyVM = new ActivityHistoryViewModel(); historyVM.ProcessHistory = app.GetActivity(id); historyVM.Process = app.GetProcess(id); var processlist = app.GetProcessList(); historyVM.ProcessList = from process in processlist select new SelectListItem { Text = process.ProcessName, Value = process.ID.ToString(), Selected = long.Equals(process.ID, id) }; var listitems = new List<SelectListItem>(); return View(historyVM); } 
0
Apr 18 '17 at 9:51 on
source share

The code below solves two problems: 1) dynamically set the selected value of the drop-down list and 2) it is more important to create a drop-down list for the indexed array in the model. the problem here is that everyone uses one instance of the select list, which is ViewBoag.List, while the array needs one instance of the pick list for each drop-down list so that the selected value can be set.

create a ViewBag variable as List (not SelectList) in the controller

// controller code
ViewBag.Role = db.LUT_Role.ToList ();

// in the view @ Html.DropDownListFor (m => m.Contacts [i] .Role, the new SelectList (ViewBag.Role, "ID", "Role", Model.Contacts [i] .Role))

0
Jun 25 '19 at 21:54
source share

In case someone is looking, I left my answer from: SelectListItem selected = true does not work in view

After finding myself to solve this problem - I had some tips along the way, but this is the solution for me. This is an extension method. I am using MVC 5 C # 4.52 is the goal. The code below sets the Selection for the first item in the list, because this is what I need, you can just skip the line and skip the enumeration - but I also wanted to make sure something returned to my SelectList from the database)

 Extension Method: 

public static class SelectListextensions {

 public static System.Web.Mvc.SelectList SetSelectedValue 

(this list System.Web.Mvc.SelectList, string value) {if (value! = zero) {var selected = list.Where (x => x.Text == value) .FirstOrDefault (); selected.Selected = true;
} return list; }
}

And for those who like a full bottom (like me), here is a use. The category of the object has a field defined as Name - this is the field that will be displayed as Text in the drop-down list. You can see this test for the Text property in the above code.

 Example Code: 

SelectList categorylist = new SelectList (dbContext.Categories, "Id", "Name");

SetSelectedItemValue (categorylist);

 select list function: 

private SelectList SetSelectedItemValue (source SelectList) {Category category = new category ();

 SelectListItem firstItem = new SelectListItem(); int selectListCount = -1; if (source != null && source.Items != null) { System.Collections.IEnumerator cenum = source.Items.GetEnumerator(); while (cenum.MoveNext()) { if (selectListCount == -1) { selectListCount = 0; } selectListCount += 1; category = (Category)cenum.Current; source.SetSelectedValue(category.Name); break; } if (selectListCount > 0) { foreach (SelectListItem item in source.Items) { if (item.Value == cenum.Current.ToString()) { item.Selected = true; break; } } } } return source; 

}

You can make it a universal all-inclusive feature / extension, but it works as it does for me

0
Aug 20 '19 at 17:13
source share



All Articles