1

我正在制作我的表单的部分视图。在其中,我想使用 3 个值显示一个下拉列表,例如:

<td>
    @Html.DropDownList("Yes", "No", "Not Applicable")
</td>

显然我不能硬编码这样的值,但这就是想法。我将仅在此视图中使用此下拉菜单,因此如果可能,我想在此处保留逻辑,唯一的事情是我想跟踪所选值,因此我想添加一些隐藏值Id,例如。在我看来有没有办法做到这一点?我考虑过传递 ViewBag 参数或类似的东西,但我真的认为必须有一个更优雅的解决方案。

4

2 回答 2

5
ViewData["myList"] = 
                new SelectList(new[] { "10", "15", "25", "50", "100", "1000" }
                .Select(x => new {value = x, text = x}), 
                "value", "text", "15");

然后在你看来:

@Html.DropDownList("myList")

或者您可以使用 linq 生成选择列表

IList<Customer> customers = repository.GetAll<Customer>();
IEnumerable<SelectListItem> selectList = 
    from c in customers
    select new SelectListItem
    {
        Selected = (c.CustomerID == invoice.CustomerID),
        Text = c.Name,
        Value = c.CustomerID.ToString()
    };

在你的情况下:

    List<SelectListItem> ls = new List<SelectListItem>();

    ls.Add(new SelectListItem() { Text = "Yes", Value = "true", Selected = true });
    ls.Add(new SelectListItem() { Text = "No", Value = "false", Selected = false });
    ls.Add(new SelectListItem() { Text = "Not Applicable", Value = "NULL", Selected = false });

    ViewData["myList"] = ls;
于 2013-05-05T21:23:38.370 回答
3

如果您只需要在 中的这些数据View,您可以在没有帮助的情况下编写:

<select name="PropertyName" id="PropertyName">
    <option value="Yes">Yes</option>
    <option value="No">No</option>
    <option value="Not Applicable">Not Applicable</option>
</select>

并选择项目jquery

或者

@Html.DropDownList(
    "PropertyName", 
    new SelectList(
        (new List {"Yes", "No", "Not Applicable"}).Select(x => new { Value = x, Text = x }),
        "Value",
        "Text",
        "SelectedValue"
    )
)

或者

<select name="PropertyName" id="PropertyName">
    @{string[] list = new string[] { "Yes", "No", "Not Applicable" };}
    @foreach (var item in list)
    {
        <option @if(item == "SelectedValue") { <text>selected="selected"</text> } value="@item">@item</option>
    }
</select>
于 2013-05-05T21:40:02.447 回答