CIA
CIA

Reputation: 302

Why is my default value for DropDownListFor not working properly?

For whatever reason, my default value for my Html.DropDownListFor isn't working:

@Html.DropDownListFor(model => model.DomainList,
    new SelectList(Model.DomainList, "DomainId", "Name", Model.SingleDomain.DomainId),
    new { @class = "form-control" })

Any idea why?

UPDATE

With the answer below, I updated my code to the following:

@Html.DropDownListFor(model => model.SelectedDomain, 
    new SelectList(Model.DomainList, "DomainId", "Name", Model.SelectedDomain),
    "Select a Domain", 
    new { @class = "form-control" })

Upvotes: 3

Views: 12304

Answers (3)

user3833081
user3833081

Reputation: 11

my problem solved when change viewbag.xxxxxxx to viewbag.xxxxxxx1 issue was hapend when model propety and viewbag property was same.

controller :

 ViewBag.serviceid = new SelectList(db.services.ToList(), "id", "titel", package.service_id);

view:

     @Html.DropDownListFor(Model => Model.service_id, ViewBag.serviceid as SelectList, htmlAttributes: new { @class = "form-control" })

Upvotes: 1

Mateut Alin
Mateut Alin

Reputation: 1295

If someone is having trouble with Html.DropdownList keep in mind that

@Html.DropDownList("Country", ViewBag.Country as List<SelectListItem>) --> doesn't select the default value

@Html.DropDownList("Countries", ViewBag.Country as List<SelectListItem>) --> selects the default value

For more details, see: http://www.binaryintellect.net/articles/69395e7d-7c7c-4318-97f5-4ea108a0da97.aspx

Upvotes: 1

Jack
Jack

Reputation: 9252

Try this:

In your ViewModel, add an integer to store the selected domain id:

public int SelectedDomainId { get; set; }

Change your DropDownListFor to:

@Html.DropDownListFor(model => model.SelectedDomainId,
    new SelectList(Model.DomainList, "DomainId", "Name", Model.SingleDomain.DomainId),
    new { @class = "form-control" })

Now on your post-back the selected id will be posted in SelectedDomainId.

Or, you could add the single domain object to your VM (to indicate which one was selected):

public Domain SelectedDomain { get; set; }

And change your DropDownListFor to:

@Html.DropDownListFor(model => model.SelectedDomain,
        new SelectList(Model.DomainList, "DomainId", "Name", Model.SingleDomain.DomainId),
        new { @class = "form-control" })

I usually use the selected ID, but I think either should work

Here is another good example:

MVC3 DropDownListFor - a simple example?

Upvotes: 8

Related Questions