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??
我怎么解决这个问题?
23 个解决方案
#1
123
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...
乍一看,我不知道你想要什么……
#2
68
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;
}
}
#3
47
Using the constructor that accepts items, dataValueField, dataTextField, selectedValue
as parameters :
使用构造函数接受项、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") %>
#4
18
Building off Thomas Stock's answer, I created these overloaded ToSelectList
methods:
基于Thomas Stock的答案,我创建了这些重载的ToSelectList方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
public static partial class Helpers
{
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, bool selectAll = false)
{
return enumerable.ToSelectList(value, value, selectAll);
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, object selectedValue)
{
return enumerable.ToSelectList(value, value, new List<object>() { selectedValue });
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, IEnumerable<object> selectedValues)
{
return enumerable.ToSelectList(value, value, selectedValues);
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, Func<T, object> text, bool selectAll = false)
{
foreach (var f in enumerable.Where(x => x != null))
{
yield return new SelectListItem()
{
Value = value(f).ToString(),
Text = text(f).ToString(),
Selected = selectAll
};
}
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, Func<T, object> text, object selectedValue)
{
return enumerable.ToSelectList(value, text, new List<object>() { selectedValue });
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, Func<T, object> text, IEnumerable<object> selectedValues)
{
var sel = selectedValues != null
? selectedValues.Where(x => x != null).ToList().ConvertAll<string>(x => x.ToString())
: new List<string>();
foreach (var f in enumerable.Where(x => x != null))
{
yield return new SelectListItem()
{
Value = value(f).ToString(),
Text = text(f).ToString(),
Selected = sel.Contains(value(f).ToString())
};
}
}
}
In your controller, you might do the following:
在控制器中,您可以执行以下操作:
var pageOptions = new[] { "10", "15", "25", "50", "100", "1000" };
ViewBag.PageOptions = pageOptions.ToSelectList(o => o, "15" /*selectedValue*/);
And finally in your View, put:
最后,在你看来,
@Html.DropDownList("PageOptionsDropDown", ViewBag.PageOptions as IEnumerable<SelectListItem>, "(Select one)")
It will result in the desired output--of course, you can leave out the "(Select one)"
optionLabel above if you don't want the first empty item:
它将产生所需的输出——当然,如果您不想要第一个空项,您可以省略上面的“(选择一)”选项标签:
<select id="PageOptionsDropDown" name="PageOptionsDropDown">
<option value="">(Select one)</option>
<option value="10">10</option>
<option selected="selected" value="15">15</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="1000">1000</option>
</select>
Update: A revised code listing can be found here with XML comments.
更新:可以在这里找到经过修改的代码列表和XML注释。
#5
12
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中设置所选的属性,但是如果您使用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:
您必须使用SelectListItem[]、文本名称、值名和SelectedValue的SelectList ctor。请注意将您想要选择的SelectListItem的值作为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"属性。那看起来像好的旧数据集;
#6
11
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" },
}
#7
10
If that's literally all you want to do then just declaring the array as string fixes the selected item problem:
如果这就是你想要做的,那么只要将数组声明为字符串就可以修复所选的项目问题:
myViewData.PageOptionsDropDown =
new SelectList(new string[] {"10", "15", "25", "50", "100", "1000"}, "15");
#8
6
It's very simple to get SelectList and SelectedValue working together, even if your property isn't a simple object like a Int, String or a Double value.
让SelectList和SelectedValue一起工作非常简单,即使您的属性不是一个简单的对象,比如Int、String或Double值。
Example:
例子:
Assuming our Region object is something like this:
假设我们的区域对象是这样的:
public class Region {
public Guid ID { get; set; }
public Guid Name { get; set; }
}
And your view model is something like:
你的视图模型是这样的
public class ContactViewModel {
public DateTime Date { get; set; }
public Region Region { get; set; }
public List<Region> Regions { get; set; }
}
You can have the code below:
你可以有以下代码:
@Html.DropDownListFor(x => x.Region, new SelectList(Model.Regions, "ID", "Name"))
Only if you override the ToString method of Region object to something like:
只有当您将区域对象的ToString方法覆盖到以下内容:
public class Region {
public Guid ID { get; set; }
public Guid Name { get; set; }
public override string ToString()
{
return ID.ToString();
}
}
This have 100% garantee to work.
这有百分之百的担保。
But I really believe the best way to get SelectList 100% working in all circustances is by using the Equals method to test DropDownList or ListBox property value against each item on items collection.
但是我真的相信让SelectList在所有电路中100%工作的最好方法是使用Equals方法来测试DropDownList或ListBox属性值对项集合上的每个项。
#9
4
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,以便它不是继承类上属性的名称。然后,需要在edit (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 say的字段,并且显示了一个国家名列表,让下拉菜单中有一个国家名的id而不是国家名的id,那么在post中,您可以使用Collection["CountryName"]做一些事情。
#10
4
I had the exact same problem. The solution is simple. Just change the "name" parameter passed to the DropDownList helper to something that does not match any of the properties existing in your ViewModel. read more here: http://www.dotnetguy.co.uk/post/2009/06/25/net-mvc-selectlists-selected-value-does-not-get-set-in-the-view
我也有同样的问题。解决方案是简单。只需将传递给DropDownList helper的“name”参数更改为与ViewModel中存在的任何属性不匹配的。阅读更多:http://www.dotnetguy.co.uk/post/2009/06/25/net-mvc-selectlists-selected-value-does-not-get-set-in-the-view
I quote the Dan Watson:
我引用丹·沃森的话:
In MVC if the view is strongly typed the selectlist’s selected option will be overridden and the selected option property set on the constructor will never reach the view and the first option in the dropdown will be selected instead (why is still a bit of a mystery).
在MVC中,如果视图是强类型的,那么selectlist的选择选项将被覆盖,而构造函数上的选择选项属性设置将永远不会到达视图,下拉菜单中的第一个选项将被选中(为什么仍然有点神秘)。
cheers!
干杯!
#11
2
All these answers look great, but seems to be that the controller is preparing data for a View in a well-known structured format vs. letting the view simply iterate an IEnumerable<> delivered via the model and build a standard select list then let DefaultModelBinder deliver the selected item back to you via an action parameter. Yes, no, why not? Separation of concerns, yes? Seems odd to have the controller to build something so UI and View specific.
所有这些答案看起来很好,但似乎是控制器是在一个著名的结构化的格式准备数据视图和视图让简单的迭代IEnumerable接口< >通过模型和建立一个标准的选择列表然后让DefaultModelBinder交付通过一个操作参数选定的项目回到你身边。是的,为什么不呢?关注点分离,对吗?让控制器构建UI和视图特定的东西看起来很奇怪。
#12
2
Simple:
简单:
string[] someName = new string[] {"10", "15", "25", "50", "100", "1000"};
myViewData.PageOptionsDropDown = new SelectList(someName, "15");
#13
1
Using your example this worked for me:
用你的例子来说,这对我很有效:
controller:
控制器:
ViewData["PageOptionsDropDown"] = new SelectList(new[] { "10", "15", "25", "50", "100", "1000" }, "15");
view:
观点:
<%= Html.DropDownList("PageOptionsDropDown")%>
#14
1
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"]) %>
#15
1
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");
#16
1
I do it like this:
我这样做:
List<SelectListItem> list = new List<SelectListItem>{
new SelectListItem {Selected = true, Text = "Select", Value = "0"},
new SelectListItem {Selected = true, Text = "1", Value = "1"},
new SelectListItem {Selected = true, Text = "2", Value = "2"}
};
return list.ToArray();
The ToArray() takes care of the problems.
ToArray()处理问题。
#17
1
If you want to pass some random text to your DropDownList, for example --Select-- you can easy do this using this code:
如果你想给下拉列表传递一些随机的文本,例如——选择——你可以用下面的代码很容易做到:
@Html.DropDownListFor(x => x.CategoryId, new SelectList(Model.Categories, "Id", "Name"), "--Select--", new { @class = "form-control" })
#18
0
It may be the case that you have some ambiguity in your ViewData:
可能你的视图数据中有一些模棱两可的地方:
Take a look Here
看一看这里
#19
0
the value selected in the model takes advantage instead of the default item. (I agree I didn't read all posts)
模型中选择的值利用了优势,而不是默认项。(我承认我没有读过所有的文章)
#20
0
I can't remember how mvc 1 was setup, but it seems that it wanted the select list named the same as the field it belonged too...
我不记得mvc 1是如何设置的,但是看起来它想要的选择列表和它所属的字段一样…
What I found, as someone kind of said above, is that my select lists weren't working in mvc2 when the ViewData they were sent as was named the same as the field.
我发现,正如上面所说的,我的选择列表并不是在mvc2中工作的,当它们被发送的ViewData被命名为该字段时。
For example:
例如:
<%= Html.DropDownListFor((model => model.ForID), (SelectList)ViewData["ForName"]) %>
< % = Html。DropDownListFor((model => model. forid), (SelectList)ViewData["ForName"]) %>
works when
工作时
<%= Html.DropDownListFor((model => model.ForID), (SelectList)ViewData["ForID"]) %>
< % = Html。DropDownListFor((model => model.ForID), (SelectList)ViewData["ForID"] %>。
does not work as the ViewData name "ForID" is named the same as the field it is working for
当ViewData名称“ForID”被命名为与它所工作的字段相同时,是否不能工作
#21
0
A possible explanation is that the selectlist value that you are binding to is not a string.
一种可能的解释是,要绑定到的selectlist值不是字符串。
So in that example, is the parameter 'PageOptionsDropDown' a string in your model? Because if it isn't then the selected value in the list wouldn't be shown.
在这个例子中,参数PageOptionsDropDown是否是模型中的字符串?因为如果它不是,那么列表中选择的值就不会显示。
#22
0
If you look in the source code for MVC 2 at the Html.DropDownList extension method, it never checks the SelectList class SelectedValue property. It will only ever try to match against your Model.
如果在Html中查看MVC 2的源代码。下拉列表扩展方法,它从不检查SelectList类SelectedValue属性。它只会尝试与你的模型匹配。
All the above are all variations on a theme, ie how do you send a bunch of data to the view to for a drop-down list & they're all as good as each other (more-or-less).
所有这些都是一个主题的变体,比如如何将一堆数据发送到视图以获取下拉列表,它们彼此都很好(或多或少)。
The problem is in the view. Either create your own DropDownList extension method that does respect the selectvalue you set, or iterate though by hand. Which ever works best for you.
问题就在眼前。要么创建自己的DropDownList扩展方法来尊重您设置的selectvalue,要么手工迭代。这对你最有效。
#23
0
If you have a collection in your model and your View is strongly type, some variation of this will work:
如果您的模型中有一个集合,并且您的视图是强类型的,那么这个集合的一些变体将会起作用:
@Html.DropDownListFor(x => x.RegionID,
new SelectList(Model.Regions,"RegionID", "RegionName", Model.RegionID))
-or-
或者,
@Html.DropDownList("RegionID",
new SelectList(Model.Regions, "RegionID", "RegionName", Model.RegionID))
#1
123
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...
乍一看,我不知道你想要什么……
#2
68
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;
}
}
#3
47
Using the constructor that accepts items, dataValueField, dataTextField, selectedValue
as parameters :
使用构造函数接受项、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") %>
#4
18
Building off Thomas Stock's answer, I created these overloaded ToSelectList
methods:
基于Thomas Stock的答案,我创建了这些重载的ToSelectList方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
public static partial class Helpers
{
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, bool selectAll = false)
{
return enumerable.ToSelectList(value, value, selectAll);
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, object selectedValue)
{
return enumerable.ToSelectList(value, value, new List<object>() { selectedValue });
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, IEnumerable<object> selectedValues)
{
return enumerable.ToSelectList(value, value, selectedValues);
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, Func<T, object> text, bool selectAll = false)
{
foreach (var f in enumerable.Where(x => x != null))
{
yield return new SelectListItem()
{
Value = value(f).ToString(),
Text = text(f).ToString(),
Selected = selectAll
};
}
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, Func<T, object> text, object selectedValue)
{
return enumerable.ToSelectList(value, text, new List<object>() { selectedValue });
}
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, object> value, Func<T, object> text, IEnumerable<object> selectedValues)
{
var sel = selectedValues != null
? selectedValues.Where(x => x != null).ToList().ConvertAll<string>(x => x.ToString())
: new List<string>();
foreach (var f in enumerable.Where(x => x != null))
{
yield return new SelectListItem()
{
Value = value(f).ToString(),
Text = text(f).ToString(),
Selected = sel.Contains(value(f).ToString())
};
}
}
}
In your controller, you might do the following:
在控制器中,您可以执行以下操作:
var pageOptions = new[] { "10", "15", "25", "50", "100", "1000" };
ViewBag.PageOptions = pageOptions.ToSelectList(o => o, "15" /*selectedValue*/);
And finally in your View, put:
最后,在你看来,
@Html.DropDownList("PageOptionsDropDown", ViewBag.PageOptions as IEnumerable<SelectListItem>, "(Select one)")
It will result in the desired output--of course, you can leave out the "(Select one)"
optionLabel above if you don't want the first empty item:
它将产生所需的输出——当然,如果您不想要第一个空项,您可以省略上面的“(选择一)”选项标签:
<select id="PageOptionsDropDown" name="PageOptionsDropDown">
<option value="">(Select one)</option>
<option value="10">10</option>
<option selected="selected" value="15">15</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="1000">1000</option>
</select>
Update: A revised code listing can be found here with XML comments.
更新:可以在这里找到经过修改的代码列表和XML注释。
#5
12
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中设置所选的属性,但是如果您使用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:
您必须使用SelectListItem[]、文本名称、值名和SelectedValue的SelectList ctor。请注意将您想要选择的SelectListItem的值作为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"属性。那看起来像好的旧数据集;
#6
11
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" },
}
#7
10
If that's literally all you want to do then just declaring the array as string fixes the selected item problem:
如果这就是你想要做的,那么只要将数组声明为字符串就可以修复所选的项目问题:
myViewData.PageOptionsDropDown =
new SelectList(new string[] {"10", "15", "25", "50", "100", "1000"}, "15");
#8
6
It's very simple to get SelectList and SelectedValue working together, even if your property isn't a simple object like a Int, String or a Double value.
让SelectList和SelectedValue一起工作非常简单,即使您的属性不是一个简单的对象,比如Int、String或Double值。
Example:
例子:
Assuming our Region object is something like this:
假设我们的区域对象是这样的:
public class Region {
public Guid ID { get; set; }
public Guid Name { get; set; }
}
And your view model is something like:
你的视图模型是这样的
public class ContactViewModel {
public DateTime Date { get; set; }
public Region Region { get; set; }
public List<Region> Regions { get; set; }
}
You can have the code below:
你可以有以下代码:
@Html.DropDownListFor(x => x.Region, new SelectList(Model.Regions, "ID", "Name"))
Only if you override the ToString method of Region object to something like:
只有当您将区域对象的ToString方法覆盖到以下内容:
public class Region {
public Guid ID { get; set; }
public Guid Name { get; set; }
public override string ToString()
{
return ID.ToString();
}
}
This have 100% garantee to work.
这有百分之百的担保。
But I really believe the best way to get SelectList 100% working in all circustances is by using the Equals method to test DropDownList or ListBox property value against each item on items collection.
但是我真的相信让SelectList在所有电路中100%工作的最好方法是使用Equals方法来测试DropDownList或ListBox属性值对项集合上的每个项。
#9
4
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,以便它不是继承类上属性的名称。然后,需要在edit (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 say的字段,并且显示了一个国家名列表,让下拉菜单中有一个国家名的id而不是国家名的id,那么在post中,您可以使用Collection["CountryName"]做一些事情。
#10
4
I had the exact same problem. The solution is simple. Just change the "name" parameter passed to the DropDownList helper to something that does not match any of the properties existing in your ViewModel. read more here: http://www.dotnetguy.co.uk/post/2009/06/25/net-mvc-selectlists-selected-value-does-not-get-set-in-the-view
我也有同样的问题。解决方案是简单。只需将传递给DropDownList helper的“name”参数更改为与ViewModel中存在的任何属性不匹配的。阅读更多:http://www.dotnetguy.co.uk/post/2009/06/25/net-mvc-selectlists-selected-value-does-not-get-set-in-the-view
I quote the Dan Watson:
我引用丹·沃森的话:
In MVC if the view is strongly typed the selectlist’s selected option will be overridden and the selected option property set on the constructor will never reach the view and the first option in the dropdown will be selected instead (why is still a bit of a mystery).
在MVC中,如果视图是强类型的,那么selectlist的选择选项将被覆盖,而构造函数上的选择选项属性设置将永远不会到达视图,下拉菜单中的第一个选项将被选中(为什么仍然有点神秘)。
cheers!
干杯!
#11
2
All these answers look great, but seems to be that the controller is preparing data for a View in a well-known structured format vs. letting the view simply iterate an IEnumerable<> delivered via the model and build a standard select list then let DefaultModelBinder deliver the selected item back to you via an action parameter. Yes, no, why not? Separation of concerns, yes? Seems odd to have the controller to build something so UI and View specific.
所有这些答案看起来很好,但似乎是控制器是在一个著名的结构化的格式准备数据视图和视图让简单的迭代IEnumerable接口< >通过模型和建立一个标准的选择列表然后让DefaultModelBinder交付通过一个操作参数选定的项目回到你身边。是的,为什么不呢?关注点分离,对吗?让控制器构建UI和视图特定的东西看起来很奇怪。
#12
2
Simple:
简单:
string[] someName = new string[] {"10", "15", "25", "50", "100", "1000"};
myViewData.PageOptionsDropDown = new SelectList(someName, "15");
#13
1
Using your example this worked for me:
用你的例子来说,这对我很有效:
controller:
控制器:
ViewData["PageOptionsDropDown"] = new SelectList(new[] { "10", "15", "25", "50", "100", "1000" }, "15");
view:
观点:
<%= Html.DropDownList("PageOptionsDropDown")%>
#14
1
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"]) %>
#15
1
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");
#16
1
I do it like this:
我这样做:
List<SelectListItem> list = new List<SelectListItem>{
new SelectListItem {Selected = true, Text = "Select", Value = "0"},
new SelectListItem {Selected = true, Text = "1", Value = "1"},
new SelectListItem {Selected = true, Text = "2", Value = "2"}
};
return list.ToArray();
The ToArray() takes care of the problems.
ToArray()处理问题。
#17
1
If you want to pass some random text to your DropDownList, for example --Select-- you can easy do this using this code:
如果你想给下拉列表传递一些随机的文本,例如——选择——你可以用下面的代码很容易做到:
@Html.DropDownListFor(x => x.CategoryId, new SelectList(Model.Categories, "Id", "Name"), "--Select--", new { @class = "form-control" })
#18
0
It may be the case that you have some ambiguity in your ViewData:
可能你的视图数据中有一些模棱两可的地方:
Take a look Here
看一看这里
#19
0
the value selected in the model takes advantage instead of the default item. (I agree I didn't read all posts)
模型中选择的值利用了优势,而不是默认项。(我承认我没有读过所有的文章)
#20
0
I can't remember how mvc 1 was setup, but it seems that it wanted the select list named the same as the field it belonged too...
我不记得mvc 1是如何设置的,但是看起来它想要的选择列表和它所属的字段一样…
What I found, as someone kind of said above, is that my select lists weren't working in mvc2 when the ViewData they were sent as was named the same as the field.
我发现,正如上面所说的,我的选择列表并不是在mvc2中工作的,当它们被发送的ViewData被命名为该字段时。
For example:
例如:
<%= Html.DropDownListFor((model => model.ForID), (SelectList)ViewData["ForName"]) %>
< % = Html。DropDownListFor((model => model. forid), (SelectList)ViewData["ForName"]) %>
works when
工作时
<%= Html.DropDownListFor((model => model.ForID), (SelectList)ViewData["ForID"]) %>
< % = Html。DropDownListFor((model => model.ForID), (SelectList)ViewData["ForID"] %>。
does not work as the ViewData name "ForID" is named the same as the field it is working for
当ViewData名称“ForID”被命名为与它所工作的字段相同时,是否不能工作
#21
0
A possible explanation is that the selectlist value that you are binding to is not a string.
一种可能的解释是,要绑定到的selectlist值不是字符串。
So in that example, is the parameter 'PageOptionsDropDown' a string in your model? Because if it isn't then the selected value in the list wouldn't be shown.
在这个例子中,参数PageOptionsDropDown是否是模型中的字符串?因为如果它不是,那么列表中选择的值就不会显示。
#22
0
If you look in the source code for MVC 2 at the Html.DropDownList extension method, it never checks the SelectList class SelectedValue property. It will only ever try to match against your Model.
如果在Html中查看MVC 2的源代码。下拉列表扩展方法,它从不检查SelectList类SelectedValue属性。它只会尝试与你的模型匹配。
All the above are all variations on a theme, ie how do you send a bunch of data to the view to for a drop-down list & they're all as good as each other (more-or-less).
所有这些都是一个主题的变体,比如如何将一堆数据发送到视图以获取下拉列表,它们彼此都很好(或多或少)。
The problem is in the view. Either create your own DropDownList extension method that does respect the selectvalue you set, or iterate though by hand. Which ever works best for you.
问题就在眼前。要么创建自己的DropDownList扩展方法来尊重您设置的selectvalue,要么手工迭代。这对你最有效。
#23
0
If you have a collection in your model and your View is strongly type, some variation of this will work:
如果您的模型中有一个集合,并且您的视图是强类型的,那么这个集合的一些变体将会起作用:
@Html.DropDownListFor(x => x.RegionID,
new SelectList(Model.Regions,"RegionID", "RegionName", Model.RegionID))
-or-
或者,
@Html.DropDownList("RegionID",
new SelectList(Model.Regions, "RegionID", "RegionName", Model.RegionID))