Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc 4 drop down default value selected

I want to select the default value in drop down list where policyId = 7 but it didn't select that value, what i am doing wrong?

Controller:

var pm = new ManagerClass();
IEnumerable<myClass> po = pm.GetDataFromDb();
IEnumerable<SelectListItem> Policies = new SelectList(po, "PolicyID", "PolicyName", new { PolicyID = 7 });
ViewBag.Policies = Policies;

View:

@Html.DropDownListFor(m => m.PolicyID, ViewBag.Policies as IEnumerable<SelectListItem>, new { @class = "dropdown-field"})
like image 376
Altaf Sami Avatar asked May 21 '13 07:05

Altaf Sami


2 Answers

It's because it's not actually selecting the value in the SelectList.

First, to make it nicer, put the items in your view model to prevent the cast (this is better practice too):

public class MyModel
{
    public int PolicyID { get; set; }
    public List<SelectListItem> Policies { get; set; }
    //rest of your model
}

Then populate it:

var model = new MyModel();
model.Policies = po
    .Select(p => new SelectListItem
    {
        Text = p.PolicyName,
        Value = p.PolicyID.ToString(),
        Selected = p.PolicyID == currentPolicyId //change that to whatever current is
    })
    .ToList();

Then in your view, do:

@Html.DropDownListFor(m => m.PolicyID, Model.Policies, new { @class = "dropdown-field"})
like image 171
mattytommo Avatar answered Oct 14 '22 05:10

mattytommo


Just set the PolicyID property on your view model to the value you want to be preselected:

var pm = new ManagerClass();
var po = pm.GetDataFromDb();
ViewBag.Policies = new SelectList(po, "PolicyID", "PolicyName");

viewModel.PolicyID = 7;
return View(viewModel);

Since your DropDownList is bound to the PolicyID property (m => m.PolicyID), then its value will be used when deciding which element to be preselected.

like image 23
Darin Dimitrov Avatar answered Oct 14 '22 04:10

Darin Dimitrov