113

How can I set the selected value of a Html.DropDownListFor? I've been having a look online and have seen that it can be achieved by using the fourth parameter so like the below:

@Html.DropDownListFor(m => m, new SelectList(Model, "Code", "Name", 0),  "Please select a country")

My select list then display like this:

<select id="ShipFromCountries" name="ShipFromCountries">
     <option value="">Please select a country</option>
     <option value="GB">United Kingdom</option>
     <option value="US">United States</option>
     ...
</select>

But for some reason United Kingdom remains selected but I want "Please select a country" to be selected.

Anyone know how I can achieve this?

EDIT

I've updated my code as there was a slight change in functionality however still seem to be encountering this problem. This is what is in my view:

@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")

1 is the Id of the option that I want selected, I have also tried with the text of the option but that also does not work.

Any ideas?

TheGeekZn
  • 3,696
  • 10
  • 55
  • 91
Ibrar Hussain
  • 1,791
  • 2
  • 15
  • 19

13 Answers13

206

Your code has some conceptual issues:

First,

@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")

When using DropDownListFor, the first parameter is the property where your selected value is stored once you submit the form. So, in your case, you should have a SelectedOrderId as part of your model or something like that, in order to use it in this way:

@Html.DropDownListFor(n => n.SelectedOrderId, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")

Second,

Aside from using ViewBag, that is not wrong but there are better ways (put that information in the ViewModel instead), there is a "little bug" (or an unspected behavior) when your ViewBag property, where you are holding the SelectList, is the same name of the property where you put the selected value. To avoid this, just use another name when naming the property holding the list of items.

Some code I would use if I were you to avoid this issues and write better MVC code:

Viewmodel:

public class MyViewModel{
   public int SelectedOrderId {get; set;}
   public SelectList OrderTemplates {get; set;}

   // Other properties you need in your view
}

Controller:

public ActionResult MyAction(){
   var model = new MyViewModel();
   model.OrderTemplates = new SelectList(db.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1);
   //Other initialization code

   return View(model);
}

In your View:

@Html.DropDownListFor(n => n.SelectedOrderId, Model.OrderTemplates, "Please select an order template")
Romias
  • 13,783
  • 7
  • 56
  • 85
  • 49
    Saved my day: "...there is a little bug when your ViewBag property where you are holding the SelectList is the same name of the property where you put the selected value. To avoid this, just use another name when naming the property holding the list of items." Thank you! – Michael A. Volz aka Flynn Mar 14 '14 at 13:17
  • 6
    This "little bug" is absolute insanity! Just wasted 2 hours of my life because of this. How can something so obvious still exist and not get patched? – cen May 02 '15 at 19:20
  • 1
    Flynn, your comment should actually be an answer. I tried crazy implementations to get my dropdownlist to work and this was the simple solution – Dwayne Hinterlang May 09 '15 at 16:34
  • 3
    _there is a little bug_? Its not a bug at all. Model binding works by binding to the value of a property and when you bind to `OrderTemplates` your attempting to bind to a `ViewBag` property which is typeof `IEnumerabe`. But a ` –  Mar 20 '16 at 01:13
  • Holy crap I would have wasted a whole day if it wasn't for this answer. Seriously that LITTLE BUG is why we should bail on the viewbag – Worthy7 Oct 04 '16 at 07:21
  • I Just ran into the "little bug" with the ViewBag name - this saved me - thanks so much – wdomains Mar 13 '22 at 01:32
  • +1 for this lovely idea `public int SelectedOrderId {get; set;}` It's way more reusable to use `int` type instead of `string` (like I was doing). – carloswm85 Jul 18 '22 at 17:44
25

For me was not working so worked this way:

Controller:

int selectedId = 1;

ViewBag.ItemsSelect = new SelectList(db.Items, "ItemId", "ItemName",selectedId);

View:

@Html.DropDownListFor(m => m.ItemId,(SelectList)ViewBag.ItemsSelect)

JQuery:

$("document").ready(function () {
    $('#ItemId').val('@Model.ItemId');
});
Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
Vinicius Sin
  • 1,571
  • 11
  • 8
  • 2
    Your controller has the wrong number of parentheses: It has one opening parenthesis and two closing parentheses. – Amos Long Mar 24 '18 at 04:59
9

When you pass an object like this:

new SelectList(Model, "Code", "Name", 0)

you are saying: the Source (Model) and Key ("Code") the Text ("Name") and the selected value 0. You probably do not have a 0 value in your source for Code property, so the HTML Helper will select the first element to pass the real selectedValue to this control.

live-love
  • 48,840
  • 22
  • 240
  • 204
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
  • This was the issue I was having. You have to place the actual value instead of the index for the last param. For example ....., "Value", "Text", "myvalue"); instead of ....., "Value", "Text", 0); – Robert Smith Feb 16 '23 at 19:04
3

Make sure that you have trim the selected value before you assigning.

//Model

public class SelectType
{
    public string Text { get; set; }
    public string Value { get; set; }
}

//Controller

var types = new List<SelectType>();
types.Add(new SelectType() { Value =  0, Text = "Select a Type" });
types.Add(new SelectType() { Value =  1, Text = "Family Trust" });
types.Add(new SelectType() { Value =  2, Text = "Unit Trust"});
ViewBag.PartialTypes = types;

//View

@Html.DropDownListFor(m => m.PartialType, new SelectList(ViewBag.PartialTypes, "Value", "Text"), new { id = "Type" })
Barney
  • 2,355
  • 3
  • 22
  • 37
Nalan Madheswaran
  • 10,136
  • 1
  • 57
  • 42
3

If you know what will be in the view, you can also set the default value from Controller as well rather then set up it into the view/cshtml file. No need to set default value from HTML side.

In the Controller file.

commission.TypeofCommission = 1;
return View(commission);

In the .cshtml file.

@Html.DropDownListFor(row => row.TypeofCommission, new SelectList(Model.commissionTypeModelList, "type", "typeName"), "--Select--")
Smit Patel
  • 2,992
  • 1
  • 26
  • 44
1

You should forget the class

SelectList

Use this in your Controller:

var customerTypes = new[] 
{ 
    new SelectListItem(){Value = "all", Text= "All"},
    new SelectListItem(){Value = "business", Text= "Business"},
    new SelectListItem(){Value = "private", Text= "Private"},
};

Select the value:

var selectedCustomerType = customerTypes.FirstOrDefault(d => d.Value == "private");
if (selectedCustomerType != null)
    selectedCustomerType.Selected = true;

Add the list to the ViewData:

ViewBag.CustomerTypes = customerTypes;

Use this in your View:

@Html.DropDownList("SectionType", (SelectListItem[])ViewBag.CustomerTypes)

-

More information at: http://www.asp.net/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

Barney
  • 2,355
  • 3
  • 22
  • 37
g.breeze
  • 1,940
  • 19
  • 24
0

Add the Controller Section

  ViewBag.Orders= new SelectList(db.Orders, "Id", "business", paramid);

Add the Html Section

   @Html.DropDownList("Orders", null)

A simple method

ibrahim ozboluk
  • 421
  • 5
  • 10
0

For me general solution :)

@{
     var selectedCity = Model.Cities.Where(k => k.Id == Model.Addres.CityId).FirstOrDefault();
     if (selectedCity != null)
     { 
         @Html.DropDownListFor(model => model.Addres.CityId, new SelectList(Model.Cities, "Id", "Name", selectedCity.Id), new { @class = "form-control" })
     }
     else
     { 
         @Html.DropDownListFor(model => model.Cities, new SelectList(Model.Cities, "Id", "Name", "1"), new { @class = "form-control" })
     }
}
vaindil
  • 7,536
  • 21
  • 68
  • 127
Hamit YILDIRIM
  • 4,224
  • 1
  • 32
  • 35
0

Linq to Dropdown with empty item, selected item (works 100%)
(Strongly Typed,Chances for error minimum) Any model changes will be reflected in the binding

Controller

public ActionResult ManageSurveyGroup()
    {
        tbl_Survey sur = new tbl_Survey();
        sur.Survey_Est = "3";

        return View(sur);
    }

View

        @{


    //Step One : Getting all the list
    var CompEstdList = (from ComType in db.tbl_CompEstdt orderby ComType.Comp_EstdYr select ComType).ToList();

    //Step Two  : Adding a no Value item **
    CompEstdList.Insert(0, new eDurar.Models.tbl_CompEstdt { Comp_Estdid = 0, Comp_EstdYr = "--Select Company Type--" });

    //Step Three : Setting selected Value if value is present
    var selListEstd= CompEstdList.Select(s => new SelectListItem { Text = s.Comp_EstdYr, Value = s.Comp_Estdid.ToString() });

        }
        @Html.DropDownListFor(model => model.Survey_Est, selListEstd)
        @Html.ValidationMessageFor(model => model.Survey_Est)

This method for binding data also possible

var selList = CompTypeList.Select(s => new SelectListItem { Text = s.CompTyp_Name, Value = s.CompTyp_Id.ToString(), Selected = s.CompTyp_Id == 3 ? true : false });
  • var selList = CompTypeList.Select(s => new SelectListItem { Text = s.CompTyp_Name, Value = s.CompTyp_Id.ToString(), Selected = s.CompTyp_Id == 3 ? true : false }); –  May 10 '16 at 09:26
0

I know this is not really an answer to the question, but I was looking for a way to initialize the DropDownList from a list on the fly in the view when I kept stumbling upon this post.

My mistake was that I tried to create a SelectList from dictionary like this:

//wrong!
@Html.DropDownListFor(m => m.Locality, new SelectList(new Dictionary<string, string>() { { Model.Locality, Model.Locality_text } }, Model.Locality, ...

I then went digging in the official msdn doc, and found that DropDownListFor doesn't necessarily require a SelectList, but rather an IEnumerable<SelectListItem>:

//right
@Html.DropDownListFor(m => m.Locality, new List<SelectListItem>() { new SelectListItem() { Value = Model.Locality, Text = Model.Locality_text, Selected = true } }, Model.Locality, new { @class = "form-control select2ddl" })

In my case I can probably also omit the Model.Locality as selected item, since its a) the only item and b) it already says it in the SelectListItem.Selected property.

Just in case you're wondering, the datasource is an AJAX page, that gets dynamically loaded using the SelectWoo/Select2 control.

Damian Vogel
  • 1,050
  • 1
  • 13
  • 19
0
public byte UserType
public string SelectUserType

You need to get one and set different one. Selected value can not be the same item that you are about to set.

@Html.DropDownListFor(p => p.SelectUserType, new SelectList(~~UserTypeNames, "Key", "Value",UserType))

I use Enum dictionary for my list, that's why there is "key", "value" pair.

Enes Okullu
  • 303
  • 3
  • 6
0

I had a similar issue, I was using the ViewBag and Element name as same. (Typing mistake)

Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87
0

This is CSS issues. I don't know why @Html.DropDownListFor in Bootstrap 4 doest work. Surely this is class design problem. Anyways the work arround is, if your Dropdown input box has CSS Padding: #px, # px; element then disable it. Hope this will work.

naz hassan
  • 81
  • 1
  • 2