使用 ViewBag 的 Asp.net mvc 下拉列表 [英] Asp.net mvc dropdown list using ViewBag

查看:18
本文介绍了使用 ViewBag 的 Asp.net mvc 下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My table in db have fields : Id,Organisation,Info.

我想制作这样的下拉列表:

I want make dropdowm list like that:

<select>
  <option value='Id there'>'Organisation there'</option>...

我正在尝试使用 ViewBag:

I'm try to do it, using ViewBag:

ViewBag.Organisations = db.Organisations.ToList(); // get all fields from table using dbContext

并在视图中:

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

我如何建立下拉列表?

推荐答案

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

You would need to create a SelectList in controller action using one of the constructors available and in view just pass it DropDownList method as parameter.

在控制器中这样做:

ViewBag.Organisations = new SelectList(db.Organisations.ToList(),"Id","Organisation");

SelectList中,我们需要在option中指定哪个属性用作value,哪个用作text我们在最后两个参数中指定的 code> 标签.

in SelectList we need to specify which property to use as value and which to use as text in the option tag which we are specifying in last two parameters.

然后在视图中你需要这样使用它:

and then in View you would need to use it this way:

@Html.DropDownList("Organization",ViewBag.Organisations as SelectList)

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

Here first parameter would be used as name of select element and second one will be used to populate the option elements in the select

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

Following is the list of overloads available for Html.DropDownList :

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

这篇关于使用 ViewBag 的 Asp.net mvc 下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆