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

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

问题描述

我在db中的表具有字段:IdOrganisationInfo.

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

我想要像这样放置dropdowm列表:

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')

我如何建立下拉列表?

How i can build dropdown list?

推荐答案

您需要创建一个构造函数可用,并且在视图中只需将其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.

在Controller中执行以下操作:

In Controller do this:

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

SelectList中的

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

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.

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

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

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

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

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 :

查看全文

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