ASP.NET MVC 3 @ Html.DropDownList用于忽略selectedValue

问题描述

|| 在我的asp.net MVC 3项目中,我想创建一个与公司相关的联系人。 您可以直接创建联系人,也可以通过公司详细信息视图添加一个新的联系人,该联系人传递了companyId以在联系人创建表单的下拉菜单中设置该公司。 问题是我无法在下拉菜单中将通过的公司作为认公司。 Global.asax
routes.MapRoute(\"contactCreate\",\"contact/toevoegen/{companyid}\",new { action = \"ContactCreate\",controller = \"Backend\",companyid = UrlParameter.Optional });
控制器方式
public ActionResult ContactCreate(int? companyid)
{
    Contact contact = new Contact();

    ViewBag.StatusList = srep.getContactStatusses();

    ViewBag.CompanyId = companyid;

    return View(contact);
}
视图
@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有一个值。 知道为什么不设置所选值吗?     

解决方法

        在执行\“ DropDownListFor \”时,它将尝试将从模型传入的值与所选值进行匹配。因此,在您的示例中,它将使用\“ bedrijf_id \”作为所选值。看起来您希望所选值来自模型之外的值。 从评论中,我认为您想要的只是一个DropDownList,如下所示:
@Html.DropDownList(\"DropDownList\",new SelectList((ViewBag.Bedrijven,\"bedrijf_id\",\"bedrijf_naam\",ViewBag.CompanyId),\"--Kies bedrijf--\") 
希望这可以帮助。