将 Html.DropDownList 与静态项绑定 [英] Bind Html.DropDownList with static items

查看:19
本文介绍了将 Html.DropDownList 与静态项绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须静态绑定一个 Html.DropDownList 和两个项目.

I have to bind an Html.DropDownList with just two items statically.

Text="Yes" Value="1"
Text="No"  Value="0"

重要的是,我必须设置文本和值字段.

The important thing is that, I have to set the text and value fields.

我该怎么做?

推荐答案

最好不要在视图中创建 SelectList.您应该在控制器中创建它并使用 ViewData 传递它.

It is a best practice not to create the SelectList in the view. You should create it in the controller and pass it using the ViewData.

示例:

var list = new SelectList(new [] 
{
    new { ID = "1", Name = "name1" },
    new { ID = "2", Name = "name2" },
    new { ID = "3", Name = "name3" },
}, 
"ID", "Name", 1);

ViewData["list"]=list;
return View();

您传递给构造函数:IEnumerable 对象、值字段、文本字段和所选值.

you pass to the constratctor: the IEnumerable objec,the value field the text field and the selected value.

在视图中:

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

这篇关于将 Html.DropDownList 与静态项绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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