DropDownListFor – 显示一个简单的字符串列表
我知道已经有很多类似的问题,但我花了好几个小时试图解决这个问题,其他答案似乎都没有帮助!
我想使用MVC在下拉列表中显示字符串列表。 这真的很难吗? 我没有“文本”和“值”分离(尽管MVC似乎需要一个) – 显示给用户的字符串是我的值。
到目前为止,我有以下内容:
控制器:
public ActionResult Index() { return View(new HomeViewModel()); }
视图模型:
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; } }
视图:
x.Items, Model.Items); %>
但我所做的一切似乎都没有显示下拉列表。 我究竟做错了什么?
<%= Html.DropDownListFor(x => x.Items, Model.Items) %>
你是令人困惑的表达和陈述。 Html帮助器返回一个字符串,因此你需要使用=
来输出’html-value’(并且在它之后没有;
)。
更新:
Items = new SelectList(new[] { new SelectListItem {Text = "One", Value = "One"}, new SelectListItem {Text = "Two", Value = "Two"}, }, "Text", "Value");
更新2:
实际上,对于您的情况,您可能会以更简单的方式进行:
public class HomeViewModel { public HomeViewModel() { Items = new SelectList(new[] { "One", "Two" }); CurrentItem = "Two"; } public SelectList Items { get; set; } public string CurrentItem { get; set; } }
并在视图中:
上述就是C#学习教程:DropDownListFor – 显示一个简单的字符串列表分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
<%= Html.DropDownListFor(x => x.CurrentItem, Model.Items) %>
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/961696.html