基于此代码(自动生成的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...
我能够通过Controller从db看到UserName
(值= Id
)的列表:
ViewBag.UserId = new SelectList(db.Users, "Id", "UserName", Test.UserId);
现在,我不希望ViewBag从数据库中读取,而是希望它列出3个不同的字符串,我将使用它来让用户选择indata(意思是,限制它们选择这3个字符串中的一个而不是写它)。
字符串我希望它列出:
我该怎么做?
答案 0 :(得分:2)
试试这个,
@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")
OR
获取模型中的价值
*(list+sizeof(int)) = 0;
答案 1 :(得分:0)
只需将您分配的内容更改为ViewBag.UserId
f.e.像这样:
var fruits = new List<string> { "Banana", "Apple", "Orange" };
ViewBag.Fruits = fruits.Select(f => new SelectListItem { Text = f, Value = f });
答案 2 :(得分:0)
这是您构建列表项的方法:
ViewBag.Fruits = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Banana", Value = 0},
new SelectListItem { Selected = false, Text = "Apple", Value = 1},
}, "Value" , "Text", 1);
答案 3 :(得分:0)
以下是使用枚举
执行此操作的另一种方法public enum Fruit { Banana, Apple, Orange }
@Html.DropDownList("FruitSelection",
new SelectList(Enum.GetValues(typeof(Fruit))),
"Select Fruit",
new { @class = "form-control" })
答案 4 :(得分:0)
MVC 控制器
private void extarct (){
CPIOFileStream sr = new CPIOFileStream( "source file" );
sr.Extract( "Distnationfolder" );
}
在视图中
ViewBag.PageSort = new List <SelectListItem> ()
{
new SelectListItem () {Value = "1", Text = "Discounts"},
new SelectListItem () {Value = "2", Text = "New Items"},
new SelectListItem () {Value = "3", Text = "Lowest Price"},
new SelectListItem () {Value = "4", Text = "Highest Price"}
};