C# 我怎样才能让这个 ASP.NET MVC SelectList 工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/781987/
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 can I get this ASP.NET MVC SelectList to work?
提问by Pure.Krome
I create a selectList in my controller, to display in the view.
我在控制器中创建了一个 selectList,以显示在视图中。
I'm trying to create it on the fly, sorta thing .. like this...
我正在尝试动态创建它,有点像这样......
myViewData.PageOptionsDropDown =
new SelectList(new [] {"10", "15", "25", "50", "100", "1000"}, "15");
It compiles, but the output is bad...
它编译,但输出很糟糕......
<select id="PageOptionsDropDown" name="PageOptionsDropDown">
<option>10</option>
<option>15</option>
<option>25</option>
<option>50</option>
<option>100</option>
<option>1000</option>
</select>
Notice how no item is selected?
注意没有项目被选中?
How can I fix this??
我怎样才能解决这个问题??
回答by mhenrixon
This is how I do it
这就是我的做法
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()
};
At second glance I'm not sure I know what you are after...
乍一看,我不确定我知道你在追求什么......
回答by ?a?da? Tekin
Using the constructor that accepts items, dataValueField, dataTextField, selectedValue
as parameters :
使用接受items, dataValueField, dataTextField, selectedValue
作为参数的构造函数:
ViewData["myList"] =
new SelectList(new[] { "10", "15", "25", "50", "100", "1000" }
.Select(x => new {value = x, text = x}),
"value", "text", "15");
Then in your view :
那么在你看来:
<%=Html.DropDownList("myList") %>
回答by KP.
回答by Thomas Stock
I use an extension method:
我使用扩展方法:
usage
用法
var departmentItems = departments.ToSelectList(d => d.Code +
" - " + d.Description,
d => d.Id.ToString(),
" - ");
var functionItems = customerFunctions.ToSelectList(f => f.Description,
f => f.Id.ToString(),
" - ");
with
和
public static class MCVExtentions
{
public static List<SelectListItem> ToSelectList<T>(
this IEnumerable<T> enumerable,
Func<T, string> text,
Func<T, string> value,
string defaultOption)
{
var items = enumerable.Select(f => new SelectListItem()
{
Text = text(f),
Value = value(f)
}).ToList();
items.Insert(0, new SelectListItem()
{
Text = defaultOption,
Value = "-1"
});
return items;
}
}
回答by murki
This is an option:
这是一个选项:
myViewData.PageOptionsDropDown = new[]
{
new SelectListItem { Text = "10", Value = "10" },
new SelectListItem { Text = "15", Value = "15", Selected = true }
new SelectListItem { Text = "25", Value = "25" },
new SelectListItem { Text = "50", Value = "50" },
new SelectListItem { Text = "100", Value = "100" },
new SelectListItem { Text = "1000", Value = "1000" },
}
回答by Cadoo
Using your example this worked for me:
使用你的例子这对我有用:
controller:
控制器:
ViewData["PageOptionsDropDown"] = new SelectList(new[] { "10", "15", "25", "50", "100", "1000" }, "15");
view:
看法:
<%= Html.DropDownList("PageOptionsDropDown")%>
回答by Tony Borf
I just ran it like this and had no problems,
我就是这样运行的,没有任何问题,
public class myViewDataObj
{
public SelectList PageOptionsDropDown { get; set; }
}
public ActionResult About()
{
myViewDataObj myViewData = new myViewDataObj();
myViewData.PageOptionsDropDown =
new SelectList(new[] { "10", "15", "25", "50", "100", "1000" }, "15");
ViewData["myList"] = myViewData.PageOptionsDropDown;
return View();
}
and
和
<%=Html.DropDownList("myList") %>
it also worked if you do this,
如果你这样做,它也有效,
public ActionResult About()
{
myViewDataObj myViewData = new myViewDataObj();
myViewData.PageOptionsDropDown =
new SelectList(new[] { "10", "15", "25", "50", "100", "1000" });
ViewData["myListValues"] = myViewData.PageOptionsDropDown;
ViewData["myList"] = "15";
return View();
}
and
和
<%=Html.DropDownList("myList",(IEnumerable<SelectListItem>)ViewData["myListValues"]) %>
回答by Tony Borf
It seems if you have a strongly typed view you need to change the ID of the dropdown so that it is NOT the name of a property on the inherrited class. You then need to put some logic in your edit (POST) method to pull off the selected value from the FORMCollection and put it on to your instance before committing your changes.
似乎如果您有一个强类型视图,您需要更改下拉列表的 ID,以便它不是继承类上的属性名称。然后,您需要在您的编辑 (POST) 方法中放入一些逻辑,以从 FORMCollection 中提取选定的值,并将其放在您的实例中,然后再提交您的更改。
This is certainly a little strange, but i tried it and it works.
这当然有点奇怪,但我试过了,它有效。
So if you class has a field called CountryId say, and you're displaying a list of country names, make the dropdown have an id of CountryName rather than CountryId, then in the post, you can do something with Collection["CountryName"].
因此,如果您的课程有一个名为 CountryId 的字段,并且您正在显示一个国家/地区名称列表,请使下拉列表的 ID 为 CountryName 而不是 CountryId,然后在帖子中,您可以使用 Collection["CountryName"] 做一些事情.
回答by Tony Borf
The problem is, SelectList works as designed. The bug is in the design. You may set the Selected Property in SelectedItem, but this will completely be ignored, if you traverse the list with the GetEnumerator() (or if Mvc does that for you). Mvc will create new SelectListItems instead.
问题是, SelectList 按设计工作。错误在于设计。您可以在 SelectedItem 中设置 Selected 属性,但是如果您使用 GetEnumerator() 遍历列表(或者如果 Mvc 为您执行此操作),这将完全被忽略。Mvc 将创建新的 SelectListItems。
You have to use the SelectList ctor with the SelectListItem[], the Text-Name, the Value-Name and the SelectedValue. Be aware to pass as SelectedValue the VALUE of SelectListItem, which you want to be selected, not the SelectListItem itself! Example:
您必须将 SelectList ctor 与 SelectListItem[]、Text-Name、Value-Name 和 SelectedValue 一起使用。请注意将要被选择的 SelectListItem 的 VALUE 作为 SelectedValue 传递,而不是 SelectListItem 本身!例子:
SelectList sl = new SelectList( new[]{
new SelectListItem{ Text="one", Value="1"},
new SelectListItem{ Text="two", Value="2"},
new SelectListItem{ Text="three", Value="3"}
}, "Text", "Value", "2" );
(not tested this, but I had the same problem)
(没有测试过,但我遇到了同样的问题)
then the 2nd option will get the selected="selected" attribute. That looks like good old DataSets ;-)
那么第二个选项将获得 selected="selected" 属性。看起来不错的旧数据集;-)
回答by Cactus
MonthRepository monthRepository = new MonthRepository();
IQueryable<MonthEntity> entities = monthRepository.GetAllMonth();
List<MonthEntity> monthEntities = new List<MonthEntity>();
foreach(var r in entities)
{
monthEntities.Add(r);
}
ViewData["Month"] = new SelectList(monthEntities, "MonthID", "Month", "Mars");