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

查看:209
本文介绍了绑定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.

我怎样才能做到这一点?

How can I do this?

推荐答案

这是不是在视图中创建选择列表的最佳实践。你应该在控制器中创建并使用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();

您传递给constratctor:了IEnumerable objec,值字段中的文本字段和选择的值

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

在View:

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

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

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