Search code examples
asp.net-mvc-3selectedvaluehtml.dropdownlistfor

ASP.NET MVC 3 @Html.DropDownListFor ignoring selectedValue


In my asp.net MVC 3 project I would like to create a contact that's related to a company.

You can either directly create a contact OR go via the company details view and add a new contact passing the companyId to set that company already in the dropdown on the contact create form.

The problem is that I can 't get the passed company as default in my dropdown.

Global.asax

routes.MapRoute("contactCreate", "contact/toevoegen/{companyid}", new { action = "ContactCreate", controller = "Backend", companyid = UrlParameter.Optional });

Controller method

public ActionResult ContactCreate(int? companyid)
{
    Contact contact = new Contact();

    ViewBag.StatusList = srep.getContactStatusses();

    ViewBag.CompanyId = companyid;

    return View(contact);
}

View

@model xxx.Models.Contact

...

        <div class="editor-label">
            @Html.LabelFor(model => model.bedrijf_id)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.bedrijf_id, new SelectList(ViewBag.Bedrijven, "bedrijf_id", "bedrijf_naam",ViewBag.CompanyId), "--Kies bedrijf--")
            @ViewBag.CompanyId
            @Html.ValidationMessageFor(model => model.bedrijf_id)
        </div>
...

@ViewBag.CompanyId has a value.

Any idea why it's not setting the selected value?


Solution

  • When doing a "DropDownListFor" it will try to match up the value passed in from the model for the selected value. So in your example it will use "bedrijf_id" as the selected value. It looks like you want the selected value to be from something outside of your model.

    From the comments I think what you want is just a DropDownList as follows:

    @Html.DropDownList("DropDownList", new SelectList((ViewBag.Bedrijven, "bedrijf_id", "bedrijf_naam", ViewBag.CompanyId), "--Kies bedrijf--") 
    

    Hope this helps.