使用ViewBag的Asp.net mvc下拉列表

I.B*_*ond 7 c# asp.net asp.net-mvc drop-down-menu

我在数据库表字段有:Id,Organisation,Info.

我想要像这样制作dropdowm列表:

<select>
  <option value='Id there'>'Organisation there'</option>...
Run Code Online (Sandbox Code Playgroud)

我试着用ViewBag做到这一点:

ViewBag.Organisations = db.Organisations.ToList(); // get all fields from table using dbContext
Run Code Online (Sandbox Code Playgroud)

在视图中:

@Html.DropDownList('I don`t know what i shoud write here, please help')
Run Code Online (Sandbox Code Playgroud)

我如何建立下拉列表?

Ehs*_*jad 13

您需要SelectList使用其中一个可用的构造函数创建一个控制器操作,并在视图中将DropDownList方法作为参数传递.

在Controller中执行此操作:

ViewBag.Organisations = new SelectList(db.Organisations.ToList(),"Id","Organisation");
Run Code Online (Sandbox Code Playgroud)

SelectList我们需要指定为要使用的财产value,并随着使用textoption,我们要指定在最后两个参数标签.

然后在View中你需要以这种方式使用它:

@Html.DropDownList("Organization",ViewBag.Organisations as SelectList)
Run Code Online (Sandbox Code Playgroud)

这里第一个参数将用作select元素的名称,第二个参数将用于填充option元素select

以下是可用于的重载列表Html.DropDownList:

https://msdn.microsoft.com/en-us/library/system.web.webpages.html.htmlhelper.dropdownlist%28v=vs.111%29.aspx?f=255&MSPPError=-2147217396


Val*_*Sky 5

我建议您使用OrganisationId属性为您的页面定义一个 ViewModel 。因此,在选择组织下拉列表的条目时将填充此值。

@model BCO.Models.SelectOrganisationViewModel

@{
    ViewBag.Title = "OrganisationInfo";
}

<div>
    @Html.DropDownListFor(o => o.OrganisationId,
        new SelectList(ViewBag.Organisations, "Id", "Name"))
</div>
Run Code Online (Sandbox Code Playgroud)

的SelectList本身预期

  • 用于填充 DropDownList 的列表
  • 值(“Id”)
  • 文本(“名称”)

作为参数。