【问题标题】:ASP.NET MVC 3 @Html.DropDownListFor ignoring selectedValueASP.NET MVC 3 @Html.DropDownListFor 忽略 selectedValue
【发布时间】:2011-05-31 09:39:41
【问题描述】:

在我的 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 有一个值。

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

【问题讨论】:

  • 在我的 ViewModel 中构建 SelectList 似乎可行...

标签: asp.net-mvc-3 selectedvalue html.dropdownlistfor


【解决方案1】:

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

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

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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多