在ASP.NET MVC标记中,设置下拉列表的最佳方法是什么?

4

我有这样的HTML...

<select id="View" name="View">
   <option value="1">With issue covers</option>
   <option value="0">No issue covers</option>
 </select>

它不允许我像这样插入代码...

<select id="View" name="View">
   <option value="1" <% ..logic code..%> >With issue covers</option>
   <option value="0" <% ..logic code..%> >No issue covers</option>
 </select>

那么设置选中的最佳方法是什么?

更新: 不使用HTML助手。


我们可能需要查看这个“逻辑代码”才能帮助您解决问题。 - yfeldblum
4个回答

7
"最好的"方法可能是使用helpers:
var selectList = new SelectList(data, "ValueProp", "TextProp", data[1].ValueProp);
... Html.DropDownList("foo", selectList)

这里的"data"可以是匿名类型的数组,例如:

var data = new[] {
  new {Key=1, Text="With issue covers"},
  new {Key=0, Text="No issue covers"}
};
// todo: pick the selected index or value based on your logic
var selectList = new SelectList(data, "Key", "Text", data[1].Key);
Writer.Write(Html.DropDownList("foo", selectList));

另一种方法可能是通过脚本在客户端选择正确的项,但显然这只适用于启用了脚本的情况。
请注意,在数据声明中缺少逗号和分号,导致其停止工作。

1
我同意Marc的建议使用helpers,但如果你必须避免使用它们,那么你可以尝试以下方法:
<select id="View" name="View">
   <option value="1" <% if (something) { %> selected <% } %> >With issue covers</option>
   <option value="0" <% if (!something) { %> selected <% } %> >No issue covers</option>
</select>

我尝试过类似的东西,但它没有起作用。我尝试了你的代码,它能工作!我肯定是做错了什么。由于IDE突出显示它看起来很奇怪,我认为你不能在那里放标记。显然我错了。谢谢! - Donny V.

1

我认为帮助程序是最好的选择。

如果您没有传递“选定值”(SelectList 构造函数中的第四个参数),则它将从 ModelState 中加载(如果有)。当您处理后续请求并希望 MVC 自动跨加载维护表单状态时,这非常方便。您可以设置条件,仅在首次加载时使用“选定值”选项进行覆盖,然后让 MVC 和 HtmlHelpers 在此之后管理状态。

视图标记:

<%= Html.DropDownList("RdfParser", ViewData["RdfParserTypes"] as SelectList) %>

控制器:

var rdfTypes = new[]
    {
        new { value = 0, text = "RDF/XML" },
        new { value = 1, text = "NTriples" },
        new { value = 2, text = "Turtle" },
        new { value = 3, text = "RDFa" }
    };
ViewData["RdfParserTypes"] = new SelectList(rdfTypes, "value", "text", rdfTypes[0]);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接