145

我正在尝试创建DropDownList一个剃刀视图。

有人会帮我解决这个问题吗?

普通 HTML5 代码:

<select id="dropdowntipo">
    <option value="Exemplo1">Exemplo1</option>
    <option value="Exemplo2">Exemplo2</option>
    <option value="Exemplo3">Exemplo3</option>
</select>

我试过这个:

@{
    var listItems = new List<ListItem> { 
        new ListItem { Text = "Exemplo1", Value = "Exemplo1" }, 
        new ListItem { Text = "Exemplo2", Value = "Exemplo2" }, 
        new ListItem { Text = "Exemplo3", Value = "Exemplo3" } 
    };
}

@Html.DropDownListFor(model => 
    model.tipo, 
    new SelectList(listItems), 
    "-- Select Status --"
)
4

12 回答 12

253
@{
   List<SelectListItem> listItems= new List<SelectListItem>();
   listItems.Add(new SelectListItem
        {
          Text = "Exemplo1",
          Value = "Exemplo1"
        });
   listItems.Add(new SelectListItem
        {
            Text = "Exemplo2",
            Value = "Exemplo2",
            Selected = true
        });
   listItems.Add(new SelectListItem
        {
            Text = "Exemplo3",
            Value = "Exemplo3"
        });
}

@Html.DropDownListFor(model => model.tipo, listItems, "-- Select Status --")
于 2013-07-18T15:21:02.720 回答
73
@{var listItems = new List<ListItem>
    {
          new ListItem { Text = "Exemplo1", Value="Exemplo1" },
          new ListItem { Text = "Exemplo2", Value="Exemplo2" },
          new ListItem { Text = "Exemplo3", Value="Exemplo3" }
    };
    }
        @Html.DropDownList("Exemplo",new SelectList(listItems,"Value","Text"))
于 2014-01-31T05:04:22.287 回答
43

你可以使用这个:

@Html.DropDownListFor(x => x.Tipo, new List<SelectListItem>
    {
                        new SelectListItem() {Text = "Exemplo1", Value="Exemplo1"},
                        new SelectListItem() {Text = "Exemplo2", Value="Exemplo2"},
                        new SelectListItem() {Text = "Exemplo3", Value="Exemplo3"}
    })  
于 2014-04-19T17:09:19.460 回答
22

//视图模型

public class RegisterViewModel
{

    public RegisterViewModel()
    {
        ActionsList = new List<SelectListItem>();
    }

    public IEnumerable<SelectListItem> ActionsList { get; set; }

    public string StudentGrade { get; set; }

  }

//枚举类:

public enum GradeTypes
{
    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H
}

//控制器动作

 public ActionResult Student()
    {
RegisterViewModel vm = new RegisterViewModel();
IEnumerable<GradeTypes> actionTypes = Enum.GetValues(typeof(GradeTypes))
                                             .Cast<GradeTypes>();
        vm.ActionsList = from action in actionTypes
                         select new SelectListItem
                         {
                             Text = action.ToString(),
                             Value = action.ToString()
                         };
        return View(vm);
    }

//查看动作

 <div class="form-group">
                                <label class="col-lg-2 control-label" for="hobies">Student Grade:</label>
                                <div class="col-lg-10">
                                   @Html.DropDownListFor(model => model.StudentGrade, Model.ActionsList, new { @class = "form-control" })
                                </div>
于 2015-05-13T04:42:13.007 回答
11

这是最简单的答案:

在您看来,只需添加:

@Html.DropDownListFor(model => model.tipo, new SelectList(new[]{"Exemplo1",
"Exemplo2", "Exemplo3"}))

在您的控制器中添加:

var exemploList= new SelectList(new[] { "Exemplo1:", "Exemplo2", "Exemplo3" });
        ViewBag.ExemploList = exemploList;

你的观点只是添加:

@Html.DropDownListFor(model => model.tipo, (SelectList)ViewBag.ExemploList )

我和 Jess Chadwick 学的

于 2015-09-21T08:37:40.300 回答
10

相信我,我已经尝试了很多选择来做到这一点 ,我在这里有答案

但我总是为前​​端和后端开发人员寻找最佳实践和迄今为止我所知道的最佳方法是for loop(是的,我不是在开玩笑)

因为当前端为您提供带有虚拟数据的 UI 页面时,他还在特定选择选项上添加了类和一些内联样式,因此hard to deal使用HtmlHelper

看看这个:

<select class="input-lg" style="">
    <option value="0" style="color:#ccc !important;">
        Please select the membership name to be searched for
    </option>
    <option value="1">11</option>
    <option value="2">22</option>
    <option value="3">33</option>
    <option value="4">44</option>
</select>

这来自前端开发人员,所以最好的解决方案是使用 for 循环

create首先或get your list来自(...)的数据在控制器动作中,并将其放入 ViewModel、ViewBag 或其他任何东西中

//This returns object that contain Items and TotalCount
ViewBag.MembershipList = await _membershipAppService.GetAllMemberships();

其次在视图中做这个简单的for循环来填充下拉列表

<select class="input-lg" name="PrerequisiteMembershipId" id="PrerequisiteMembershipId">
    <option value="" style="color:#ccc !important;">
        Please select the membership name to be searched for
    </option>
    @foreach (var item in ViewBag.MembershipList.Items)
    {
        <option value="@item.Id" @(Model.PrerequisiteMembershipId == item.Id ? "selected" : "")>
            @item.Name
        </option>
    }
</select>

这样你就不会破坏 UI 设计,而且它的简单、容易和更具可读性

即使您没有使用剃须刀,也希望这对您有所帮助

于 2016-11-06T09:50:58.593 回答
8

Using an array would be a little more efficient than creating a list.

@Html.DropDownListFor(x => x.Tipo, new SelectListItem[]{
                new SelectListItem() {Text = "Exemplo1", Value="Exemplo1"},
                new SelectListItem() {Text = "Exemplo2", Value="Exemplo2"},
                new SelectListItem() {Text = "Exemplo3", Value="Exemplo3"}})
于 2015-02-03T21:34:19.420 回答
7
@{
List<SelectListItem> listItems= new List<SelectListItem>();
listItems.Add(new SelectListItem
    {
      Text = "One",
      Value = "1"
    });
listItems.Add(new SelectListItem
    {
        Text = "Two",
        Value = "2",
    });
listItems.Add(new SelectListItem
    {
        Text = "Three",
        Value = "3"
    });
listItems.Add(new SelectListItem
{
   Text = "Four",
   Value = "4"
});
listItems.Add(new SelectListItem
{
   Text = "Five",
   Value = "5"
});
}
@Html.DropDownList("DDlDemo",new SelectList(listItems,"Value","Text"))

参考:-在 MVC 4 razor 示例中创建下拉列表

于 2015-04-22T06:40:32.673 回答
4

如果您使用的是 ASP.net 5 (MVC 6) 或更高版本,那么您可以使用新的 Tag Helpers以获得非常好的语法:

<select asp-for="tipo">
    <option value="Exemplo1">Exemplo1</option>
    <option value="Exemplo2">Exemplo2</option>
    <option value="Exemplo3">Exemplo3</option>
</select>
于 2015-03-26T22:14:44.303 回答
4

就用这个

public ActionResult LoadCountries()
{
     List<SelectListItem> li = new List<SelectListItem>();
     li.Add(new SelectListItem { Text = "Select", Value = "0" });
     li.Add(new SelectListItem { Text = "India", Value = "1" });
     li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });
     li.Add(new SelectListItem { Text = "China", Value = "3" });
     li.Add(new SelectListItem { Text = "Austrila", Value = "4" });
     li.Add(new SelectListItem { Text = "USA", Value = "5" });
     li.Add(new SelectListItem { Text = "UK", Value = "6" });
     ViewData["country"] = li;
     return View();
}

并在视图中使用以下内容。

 @Html.DropDownList("Country", ViewData["country"] as List<SelectListItem>)

如果您想从 Dataset 获取数据并将这些数据填充到列表框中,请使用以下代码。

List<SelectListItem> li= new List<SelectListItem>();
for (int rows = 0; rows <= ds.Tables[0].Rows.Count - 1; rows++)
{
    li.Add(new SelectListItem { Text = ds.Tables[0].Rows[rows][1].ToString(), Value = ds.Tables[0].Rows[rows][0].ToString() });
}
ViewData["FeedBack"] = li;
return View();

并考虑编写以下代码。

@Html.DropDownList("FeedBack", ViewData["FeedBack"] as List<SelectListItem>)
于 2015-12-23T14:32:21.040 回答
3

这也可以像

@model IEnumerable<ItemList>

<select id="dropdowntipo">
    <option value="0">Select Item</option>
    
    @{
      foreach(var item in Model)
      {
        <option value= "@item.Value">@item.DisplayText</option>
      }
    }

</select>

于 2019-03-04T15:42:36.143 回答
0

List<tblstatu> status = new List<tblstatu>();
            status = psobj.getstatus();
            model.statuslist = status;
            model.statusid = status.Select(x => new SelectListItem
            {
                Value = x.StatusId.ToString(),
                Text = x.StatusName
            });


  @Html.DropDownListFor(m => m.status_id, Model.statusid, "Select", new { @class = "form-control input-xlarge required", @type = "text", @autocomplete = "off" })

于 2016-04-04T07:52:58.660 回答