C# 如何在 MVC Html.DropDownList() 中添加静态项目列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/867117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add static list of items in MVC Html.DropDownList()
提问by GONeale
I would like to assign a static list of items in a SelectList()
to a Html.DropDownList()
in ASP.NET MVC, what is the best practice?
我想将 a 中的静态项目列表分配给ASP.NET MVC中的SelectList()
a Html.DropDownList()
,最佳实践是什么?
I was about to try to find a way to use new SelectList(new {key = "value"}...
but one, that didn't work, and two, would I be breaking a law here, should my static list be declared in ViewData
anyway and passed as IList/IENumerable
?
我正要尝试找到一种使用方法,new SelectList(new {key = "value"}...
但一个没有用,第二个,我会在这里违反法律吗,我的静态列表是否应该以ViewData
任何方式声明并作为传递IList/IENumerable
?
采纳答案by GONeale
OK I decided to take my own advice, and this should be defined in the controller:
好吧,我决定采纳我自己的建议,这应该在控制器中定义:
FYI, I just returned:
仅供参考,我刚回来:
PageData data = new PageData()
{
Formats = new[]
{
new { ID = "string", Name = "Text" },
new { ID = "int", Name = "Numeric" },
new { ID = "decimal", Name = "Decimal" },
new { ID = "datetime", Name = "Date/Time" },
new { ID = "timespan", Name = "Stopwatch" }
},
.............
};
return View(data);
... (ignore context) and in the View ASPX side:
...(忽略上下文)并在 View ASPX 端:
<%= Html.DropDownList("type.field", new SelectList(ViewData.Model.Formats, "ID", "Name"...
If anyone has a more optimal way of doing this I'll be happy to accept their answer.
如果有人有更好的方法来做到这一点,我会很乐意接受他们的回答。
回答by GONeale
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.
最好不要在视图中创建 SelectList。您应该在控制器中创建它并使用 ViewData 传递它。
Example:
例子:
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();
you pass to the constructor: the IEnumerable object, the value field the text field and the selected value.
您传递给构造函数:IEnumerable 对象、值字段、文本字段和所选值。
in the View:
在视图中:
<%=Html.DropDownList("list",ViewData["list"] as SelectList) %>
回答by Jules Bartow
All MVC noobs initially avoid the 'M' word, but it does kinda start at the beginning of the MVC acronym. So maybe, just maybe, you might want to start your solution with a Model... just saying.
所有 MVC 新手最初都避免使用“M”这个词,但它确实是从 MVC 首字母缩略词的开头开始的。所以也许,只是也许,你可能想用一个模型开始你的解决方案......只是说。
Do not Repeat Yourself (DRY). You're going to end up copying and pasting the "new PageData()" to each and every Controller that passes the option list to a View. Then you're going to want to delete or add an option and have to edit every controller's PageData.
不要重复自己(干)。您最终将复制并粘贴“new PageData()”到每个将选项列表传递给视图的控制器。然后,您将要删除或添加一个选项,并且必须编辑每个控制器的 PageData。
Moreover, you want to type the least amount of code with the fewest unnecessarily verbose "add"s, "new"s, "IS"s, and "Name"s. Because you only have a key-value pair in the select option (and/or a radio button list), use the lightest data structure possible, i.e. a Dictionary --in your Model.
此外,您希望以最少的不必要冗长的“添加”、“新”、“IS”和“名称”键入最少的代码。因为您在选择选项(和/或单选按钮列表)中只有一个键值对,所以尽可能使用最轻量的数据结构,即在您的模型中使用字典。
Then simply reference the Model in the Controller and convert the Dictionary to a SelectList in the View using a DropDownListFor containing a LINQ Lambda expression.
然后简单地引用控制器中的模型,并使用包含 LINQ Lambda 表达式的 DropDownListFor 将字典转换为视图中的 SelectList。
Intimidated? You're not alone. I certainly was. Here's an example I used to teach myself the M, the V, and the C:
恐吓?你不是一个人。我当然是。这是我用来自学 M、V 和 C 的示例:
The Model part of MVC:
MVC的模型部分:
using System.Web.Security;
using System.Collections.Generic;
using System.Text;
using System.Linq.Expressions;
using System.Web.Routing;
using System.Web.Helpers;
using System.Web.Mvc.Html;
using MvcHtmlHelpers;
using System.Linq;
// EzPL8.com is the company I work for, hence the namespace root.
// EzPL8 increases the brainwidths of waiters and bartenders by augmenting their "memories" with the identifies of customers by name and their food and drink preferences.
// This is pedagogical example of generating a select option display for a customer's egg preference.
namespace EzPL8.Models
{
public class MyEggs
{
public Dictionary<int, string> Egg { get; set; }
public MyEggs() //constructor
{
Egg = new Dictionary<int, string>()
{
{ 0, "No Preference"}, //show the complete egg menu to customers
{ 1, "I hate eggs"}, //Either offer an alternative to eggs or don't show eggs on a customer's personalized dynamically generated menu
//confirm with the customer if they want their eggs cooked their usual preferred way, i.e.
{ 2, "Over Easy"},
{ 3, "Sunny Side Up"},
{ 4, "Scrambled"},
{ 5, "Hard Boiled"},
{ 6, "Eggs Benedict"}
};
}
}
The Controller is now fairly simple, just passing the model. It avoids creating an isolated concept, which probably isn't isolated to just one page.:
控制器现在相当简单,只需传递模型。它避免了创建一个孤立的概念,它可能不仅仅局限于一页。:
public ActionResult Index()
{
var model = new EzPL8.Models.MyEggs();
return View(model);
}
The View uses DropDownListFor (instead of DropDownList) and a Lambda expression for strong typing in the event refactoring is required:
视图使用 DropDownListFor(而不是 DropDownList),并且需要在事件重构中使用 Lambda 表达式进行强类型:
@Html.DropDownListFor(m => m.Egg, new SelectList( Model.Egg, "Key", "Value"))
Voilà, the resulting HTML:
瞧,生成的 HTML:
<select id="Egg" name="Egg">
<option value="0">No Preference</option>
<option value="1">I hate eggs</option>
<option value="2">Over Easy</option>
<option value="3">Sunny Side Up</option>
<option value="4">Scrambled</option>
<option value="5">Hard Boiled</option>
<option value="6">Eggs Benedict</option>
</select>
Note: don't get confused by the VALUE in <option value="6">
, which is the Key from the dictionary, from the "Value" in the SelectList(), which is the text/title (e.g. Eggs Benedict) that ends up between the option tags.
注意:不要被 VALUE in 混淆<option value="6">
,它是字典中的键,来自 SelectList() 中的“值”,它是最终在选项标签之间的文本/标题(例如 Eggs Benedict)。
Use Case: To minimize traffic between the application and the database I created a static list to avoid a database query for the drop down list that rarely, if ever changes. However, change is inevitable and six-months from now a diner at my customer's restaurant dies; not because of the green ham, but because they were allergic to eggs and the cook mixed some in with their waffles.
用例:为了最大限度地减少应用程序和数据库之间的流量,我创建了一个静态列表,以避免对下拉列表进行数据库查询,这种查询很少发生变化。然而,变化是不可避免的,六个月后,我客户餐厅的一位用餐者去世了;不是因为绿色火腿,而是因为他们对鸡蛋过敏,厨师在他们的华夫饼中混了一些。
The restaurant needs their customer info updated to include food allergies immediately. While they love repeat customers, they're not cool with dead customers coming back as zombies that have no way to pay because their credit cards were cancelled.
餐厅需要立即更新客户信息以包括食物过敏。虽然他们喜欢回头客,但他们并不喜欢死去的顾客作为僵尸回来,因为他们的信用卡被取消了,他们无法付款。
Rhetorical Question: Should I modify all the controllers and views related to customer egg preferences? Or simply insert { 7, "Allergic to Eggs"} into the model?
反问:我应该修改与客户鸡蛋偏好相关的所有控制器和视图吗?或者简单地将 { 7, "Allergic to Eggs"} 插入模型中?
Another Rhetorical Question: Aren't omelettes eggs? Do you want to add {8, "Omelette, Western"}, {9, "Omelette, Mushroom-Feta-Spinach"} once to the model and have the new additions automagically propagate throughout all dropdown lists in all the views that use them?
另一个反问:煎蛋不是煎蛋吗?您是否要向模型添加一次 {8, "Omelette, Western"}, {9, "Omelette, Mushroom-Feta-Spinach"} 并让新添加的内容在使用它们的所有视图中的所有下拉列表中自动传播?
Bottom line(s)This is probably way more than you asked for, ...but you did say MVC, not just VC:
1. Use a Model in *M*VC.
2. Use a dictionary in the Model when a select list is based on nothing more than a "primary key" and a title.
3. If your static list doesn't jive with a database Lookup table somewhere, your app probably isn't very useful. When you add an option to a static list, more than likely you'll also need to perform an insert to the Lookup table to avoid a primary key/foreign key relationship integrity error with other tables in the database.
4. Use lambda and strongly typed data structures to avoid errors and get typeahead support.
底线这可能比您要求的要多得多,...但您确实说的是 MVC,而不仅仅是 VC:
1. 在 * M* VC 中使用模型。2. Use a dictionary in the Model when a select list is based on nothing more than a "primary key" and a title. 3. 如果您的静态列表在某处没有与数据库查找表配合使用,则您的应用程序可能不是很有用。当您向静态列表添加选项时,您很可能还需要对 Lookup 表执行插入操作,以避免与数据库中的其他表发生主键/外键关系完整性错误。4. 使用 lambda 和强类型数据结构来避免错误并获得预先输入的支持。