DropDownListFor - 显示一个简单的字符串列表 [英] DropDownListFor - display a simple list of strings
问题描述
我知道有很多类似的问题了,但我花了几个小时试图弄清楚这一点,并没有其他的答案似乎帮助!
我只想显示使用MVC串的在下拉列表中的列表。这是真的那么难吗?我没有一个文本和价值的分离(athough MVC似乎需要一个) - 显示给用户的字符串是我的价值
我已经走到这一步,以下内容:
控制器:
公众的ActionResult指数()
{
返回查看(新HomeViewModel());
}
视图模型:
公共类HomeViewModel
{
公共HomeViewModel()
{
项目=新的SelectList(新[]
{
新SelectListItem的{text =一,值=一},
新SelectListItem的{text =二,值=二},
});
} 公众的SelectList项目{搞定;组; }
}
查看:
<使用%(Html.BeginForm()){%GT;
<%Html.DropDownListFor(X => x.Items,Model.Items); %GT;
<输入类型=提交值=走! />
<%}%GT;
但什么我似乎导致下拉列表中显示。我在做什么错了?
<%= Html.DropDownListFor(X => x.Items,Model.Items)%GT;
您混淆前pressions和语句。在HTML帮助返回一个字符串,所以你需要使用 =
来输出HTML的价值(没有;
后话)。
更新:
产品=新的SelectList(新[]
{
新SelectListItem的{text =一,值=一},
新SelectListItem的{text =二,值=二},
},文本,值);
更新2:
其实你的情况下,你可能会做,在一个更简单的方式:
公共类HomeViewModel
{
公共HomeViewModel()
{
项目=新的SelectList(新[] {一,二});
CURRENTITEM =二;
} 公众的SelectList项目{搞定;组; }
公共字符串CURRENTITEM {搞定;组; }
}
和在视图:
<%= Html.DropDownListFor(X => x.CurrentItem,Model.Items)%GT;
I know there are many similar questions already, but I've spent hours trying to figure this out and none of the other answers seem to help!
I want to just display a list of strings in a drop-down list using MVC. Is this really so difficult? I don't have a "Text" and "Value" separation (athough MVC appears to require one) - the string displayed to the user is my value.
I've got the following so far:
Controller:
public ActionResult Index()
{
return View(new HomeViewModel());
}
ViewModel:
public class HomeViewModel
{
public HomeViewModel()
{
Items = new SelectList(new[]
{
new SelectListItem { Text = "One", Value = "One" },
new SelectListItem { Text = "Two", Value = "Two" },
});
}
public SelectList Items { get; set; }
}
View:
<% using (Html.BeginForm()) { %>
<% Html.DropDownListFor(x => x.Items, Model.Items); %>
<input type="submit" value="Go!" />
<% } %>
But nothing I do seems to result in a drop down list being displayed. What am I doing wrong?
<%= Html.DropDownListFor(x => x.Items, Model.Items) %>
You are confusing expressions and statements. The Html helper returns a string, thus you need to use =
to output the 'html-value' (and no ;
after it).
Update:
Items = new SelectList(new[]
{
new SelectListItem {Text = "One", Value = "One"},
new SelectListItem {Text = "Two", Value = "Two"},
}, "Text", "Value");
Update 2:
Actually for your case you might do it in an even simpler fashion:
public class HomeViewModel
{
public HomeViewModel()
{
Items = new SelectList(new[] { "One", "Two" });
CurrentItem = "Two";
}
public SelectList Items { get; set; }
public string CurrentItem { get; set; }
}
And in the View:
<%= Html.DropDownListFor(x => x.CurrentItem, Model.Items) %>
这篇关于DropDownListFor - 显示一个简单的字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!