DropDownListFor - 显示一个简单的字符串列表 [英] DropDownListFor - display a simple list of strings

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

问题描述

我知道已经有很多类似的问题,但我花了几个小时试图弄清楚这一点,但其他答案似乎都没有帮助!

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!

我只想在使用 MVC 的下拉列表中显示字符串列表.这真的有那么难吗?我没有文本"和值"分离(尽管 MVC 似乎需要一个) - 显示给用户的字符串是我的值.

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:

控制器:

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; }
}

查看:

<% 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) %>

你混淆了表达式和语句.Html helper 返回一个字符串,因此您需要使用 = 来输出 'html-value'(并且后面没有 ;).

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).

更新:

Items = new SelectList(new[]
                       {
                           new SelectListItem {Text = "One", Value = "One"},
                           new SelectListItem {Text = "Two", Value = "Two"},
                       }, "Text", "Value");

更新 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; }
}

在视图中:

<%= Html.DropDownListFor(x => x.CurrentItem, Model.Items) %>

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

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