MVC-在DropDownList中显示字符串列表 [英] MVC - Show list of strings in DropDownList

查看:77
本文介绍了MVC-在DropDownList中显示字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于以下代码(Visual Studio中自动生成的Control/View代码):

Based on this code (auto-generated Control/View code from Visual Studio):

<div class="form-group">
    @Html.LabelFor(model => model.Type, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @*Comment: Want to replace EditorFor to DropDownList("Banana, "Apple", "Orange"*@
        @Html.EditorFor(model => model.Type, new { htmlAttributes = new { @class = "form-control" } })*@
        @Html.ValidationMessageFor(model => model.Type, "", new { @class = "text-danger" })
    </div>
</div>

我想添加类似的内容:

@Html.DropDownList("UserId", null, htmlAttributes: new { @class = "form-control" })

(也是自动生成的代码,但用于 UserId ),而不是 @ html.EditorFor ...

(also auto-generated code, but for UserId) instead of @html.EditorFor...

我能够通过Controller从数据库中看到 UserName (值= Id )的列表:

I was able to see list of UserName(value = Id) from db via Controller:

ViewBag.UserId = new SelectList(db.Users, "Id", "UserName", Test.UserId);

现在,我不希望ViewBag从数据库中读取,而是希望它列出3个不同的字符串,我将使用它们让用户选择indata(意思是,将它们限制为从这3个字符串中选择一个,而不是编写它).

Now, I don't want that ViewBag read from database, instead I want it to list 3 different strings that I will use to let user to chose for indata(meaning, limit them to choice one of these 3 string instead writing it).

我要列出的字符串:

  • 香蕉"
  • 苹果"
  • 橙色"

我该怎么做?

推荐答案

尝试一下,

@Html.DropDownList("DropDown", new List<SelectListItem>
                                 { new SelectListItem { Text = "Banana", Value = "1", Selected=true},
                                   new SelectListItem { Text = "Apple", Value = "2"},
                                   new SelectListItem { Text = "Orange", Value = "3"}
                                   }, "Select Fruit")

在模型中获取价值

@Html.DropDownListFor(x => x.Id, new List<SelectListItem>
                                 { new SelectListItem { Text = "Banana", Value = "1", Selected=true},
                                   new SelectListItem { Text = "Apple", Value = "2"},
                                   new SelectListItem { Text = "Orange", Value = "3"}
                                   }, "Select Fruit")

这篇关于MVC-在DropDownList中显示字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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