Create DropDownListFor from SelectList with default value

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.


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;