10

I have a dropdownlistfor:

 @Html.DropDownListFor(model => model.Item.Item.Status, new SelectList(@Model.AllStatus, "id", "Description"), new { id = "statusDropdown" })
 @Html.ValidationMessageFor(model => model.Item.Item.Status)

HTML output:

<select id="statusDropdown" class="valid" name="Item.Item.Status" data-val-required="The Status field is required." data-val-number="The field Status must be a number." data-val="true">
<option value="2">Completed by Admin</option>
<option value="3">General Error</option>
<option value="4">New</option>
</select>

How can I update this code to set a default selected option? E.G.

<option value="4" selected>New</option>

I tried:

 @Html.DropDownListFor(model => model.Item.Item.Status, new SelectList(@Model.AllStatus, "id", "Description",@Model.SelectedStatusIndex), new { id = "statusDropdown" })

@Model.SelectedStatusIndex has a value of 4, but does not change the default option to New.

I also tried:

@Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.AllStatus, "id", "Description"), new { id = "statusDropdown" })
@Html.ValidationMessageFor(model => model.Item.Item.Status)

This selects the default option "New", but model.Item.Item.Status is not set by the dropdown on HTTP POST.

Other Detail:

model.Item.Item.Status is an int. @Model.AllStatus is a SQL table that lists all available status options.

P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348

6 Answers6

16

There exist already some discussions about that here or there. One of the problems might be using a different type than string for the key value. I had similar problems in past and I know that i solved it like this - explicitly setting the Selected property when preparing the list (in your case, AlLStatus).

Would mean, for your case (in controller action):

IEnumerable<SelectListItem> selectList = 
from s in allStatus // where ever you get this from, database etc.
select new SelectListItem
{
    Selected = (s.id == model.Item.Item.Status),
    Text = cs.Description,
    Value = s.id.ToString()
};
model.AllStatus = selectList;
Community
  • 1
  • 1
thmshd
  • 5,729
  • 3
  • 39
  • 67
6

This is in addition to the answers above. This is how I would have done it.

The view model is there to represent your data. So for a single drop down list I would have the following:

public class MyViewModel
{
     public int StatusId { get; set; }

     public IEnumerable<Status> Statuses { get; set; }
}

And the Status class would look like this:

public class Status
{
     public int Id { get; set; }

     public string Description { get; set; }
}

The controller's action method to handle the view:

public class MyController
{
     private readonly IStatusService statusService;

     public MyController(IStatusService statusService)
     {
          this.statusService = statusService;
     }

     public ActionResult MyActionMethod()
     {
          MyViewModel viewModel = new MyViewModel
          {
               Statuses = statusService.GetAll(),
               StatusId = 4 // Set the default value
          };

          return View(viewModel);
     }
}

The view will look like this:

@model MyProject.ViewModels.MyViewModel

@Html.DropDownListFor(
     x => x.StatusId,
     new SelectList(Model.Statuses, "Id", "Description", Model.StatusId),
     "-- Select --"
)
@Html.ValidationMessageFor(x => x.StatusId)

There you go.

Brendan Vogt
  • 25,678
  • 37
  • 146
  • 234
3

I ended up using a variant of thomasjaworski's answer.

View:

@Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.StatusSelectList, "Value", "Text"), new { id = "statusDropdown" })

ViewModel constructor

        StatusSelectList = AllStatus.Select(x =>
                                        new StatusSelectListItem
                                        {
                                            Text = x.Description,
                                            Value = x.id.ToString()
                                        }).ToList();

        this.SelectedStatusIndex = 2;//Default Status is New

Controller on HTTP POST

I set model.Item.Item.Status seperately from the dropdown itself:

model.Item.Item.Status = model.SelectedStatusIndex;

because the dropdown set's the value of the expression passed as the first argument:

@Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.StatusSelectList, "Value", "Text"), new { id = "statusDropdown" })

In this case model.SelectedStatusIndex is what is set by the dropdown. This controller implementation is what I found to be tricky.

P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
  • Thanks for posting your solution! – thmshd Jun 20 '13 at 19:36
  • 1
    P.S. If you use @Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.StatusSelectList, "Value", "Text")) the id of the select list will be SelectedStatusIndex.... additionally if you use @Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.StatusSelectList, "Value", "Text"), "Please Select") it will put Please Select as the first entry. – Paul Zahra Sep 23 '16 at 15:11
  • Yes, but how would you assign "Please Select" as a value of -1 ? – JoshYates1980 Apr 26 '17 at 14:01
1

You can use "Insert" for adding default value of Dropdown and add it to your Dynamic list : By this way you don't need to use Razor in your View.

List<Y> m = X.GetList();
m.Insert(0, new Y{ Name = "--Select--" });
keivan kashani
  • 1,263
  • 14
  • 15
0
SelectList ProductSizeList = new SelectList(_context.Sizes, "SizeId", "SizeName");

//after you create the selectList you have to create the default select list item            
SelectListItem AllSize = new SelectListItem("All Size", "0");

// and after this you add this item to the begin of the selectlist
ViewData["SizeId"] = ProductSizeList.Prepend(AllSize);
Ishaan Javali
  • 1,711
  • 3
  • 13
  • 23
0

I assign DropDownListFor's expression with value which is already defined in List. It works for me. I use List<SelectListItem> Model.IncidentPriorityList for ddwn's selectlist.

Model.incident.INCIDENT_PRIORITY_ID = Model.DefaultParameterId;
@Html.DropDownListFor(m => m.incident.INCIDENT_PRIORITY_ID, Model.IncidentPriorityList, "Select", new { @class = "form-control selectpicker", id = "drpPriority", @required = true })
gkhantaskin
  • 24
  • 1
  • 4