2

在我的 asp.net MVC 3 项目中,我想创建一个与公司相关的联系人。

您可以直接创建联系人,也可以通过公司详细信息视图添加一个新联系人,并传递companyId以将该公司设置在联系人创建表单的下拉列表中。

问题是我无法在我的下拉列表中将通过的公司设为默认值。

全球.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 有一个值。

知道为什么它没有设置选定的值吗?

4

1 回答 1

1

在执行“DropDownListFor”时,它将尝试匹配从模型传入的值与所选值。因此,在您的示例中,它将使用“bedrijf_id”作为选定值。看起来您希望所选值来自模型之外的东西。

从评论中我认为你想要的只是一个 DropDownList 如下:

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

希望这可以帮助。

于 2011-08-23T05:22:09.637 回答