C# 实例化后在 SelectList 中设置选定的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/301854/
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
Set selected value in SelectList after instantiation
提问by Boris Callens
Am I right to think that there is no way to set the selected value in the C# class SelectList after it is created? Isn't that a bit silly?
我认为在创建 C# 类 SelectList 后无法在其中设置所选值是否正确?是不是有点傻?
采纳答案by awrigley
I think you are fighting the framework. The data going into your views should be created at the Last Possible Minute (LPM).
我认为您正在与框架作斗争。进入您的视图的数据应在最后可能的分钟 (LPM) 创建。
Thinking this way, a SelectList
is a type to feed the DropDownList
HTML helper. It is NOT a place to store data while you decide how to process it.
以这种方式思考, aSelectList
是一种提供DropDownList
HTML 帮助程序的类型。当您决定如何处理数据时,它不是存储数据的地方。
A better solution would be to retrieve your data into a List<T>
and then initialize the SelectList
(s) when you need to. An immediate benefit of this practice is that it allows you to reuse your List<T>
for more than one DropDownList
, such as:
更好的解决方案是将数据检索到 a 中List<T>
,然后SelectList
在需要时初始化(s)。这种做法的一个直接好处是它允许您重复使用List<T>
多个DropDownList
,例如:
Country of birth
Country of residence
These SelectLists
all use the Countries list of type List<Country>
.
这些SelectLists
都使用类型为 的国家列表List<Country>
。
You can use your List<T>
at the 'last minute' like in this example:
你可以List<T>
在“最后一分钟”使用你的,就像在这个例子中一样:
public class TaxCheatsFormViewModel
{
private List<Country> countries { get; set; }
public TaxCheat Cheat { get; private set; }
public SelectList CountryOfBirth { get; private set; }
public SelectList CountryOfResidence { get; private set; }
public SelectList CountryOfDomicile { get; private set; }
public TaxCheatsFormViewModel(TaxCheat baddie)
{
TaxCheat = baddie;
countries = TaxCheatRepository.GetList<Country>();
CountryOfBirth = new SelectList(countries, baddie.COB);
CountryOfResidence = new SelectList(countries, baddie.COR);
CountryOfDomicile = new SelectList(countries, baddie.COD);
}
}
The point being that you should keep your data in a List<T>
till you really need to output it; the last possible minute (LPM).
关键是你应该把你的数据保存在一个List<T>
直到你真的需要输出它为止;最后一分钟 (LPM)。
回答by Tor Haugen
You mean client-side, in the browser?
你的意思是客户端,在浏览器中?
var select = document.getElementById('mySelect');
select.options[newIndex].selected = true;
回答by GalacticCowboy
The "SelectedValue" property is read-only. Setting it in the constructor is the only way.
“SelectedValue”属性是只读的。在构造函数中设置它是唯一的方法。
Tor, the SelectList is an ASP.NET MVC construct used to create a drop-down list. Doing it your way should work too, but the SelectList should do it for you (and not in JS) if done properly.
Tor,SelectList 是用于创建下拉列表的 ASP.NET MVC 构造。按照你的方式做也应该有效,但如果做得好, SelectList 应该为你做(而不是在 JS 中)。
回答by Ben Mills
I think you can do this in the controller. If you are going to render a drop down list with name/ID StateCode, then you can set the selected state using this code after the SelectList is created:
我认为您可以在控制器中执行此操作。如果您要呈现带有名称/ID StateCode 的下拉列表,则可以在创建 SelectList 后使用以下代码设置选定状态:
ViewData["StateCode"] = "VT";
ViewData["StateCode"] = "VT";
It seems that the drop down list HTML helper looks for a ViewData item with the same name as the drop down list that's being created.
似乎下拉列表 HTML 帮助程序查找与正在创建的下拉列表同名的 ViewData 项。
I don't think I like using this technique, but it does seem to work.
我不认为我喜欢使用这种技术,但它似乎确实有效。
I do agree that the SelectList class is a little weak at the moment. I'd like to be able to create a SelectList and then select a value later by either value or text.
我确实同意 SelectList 类目前有点弱。我希望能够创建一个 SelectList,然后稍后通过值或文本选择一个值。
回答by linh1987
The SelectList object is readonly after it was created. if you want to select something you better do it like:
SelectList 对象在创建后是只读的。如果你想选择一些东西,你最好这样做:
<%= Html.DropDownList("clientId", ViewData["clients"] as List<SelectListItem>,)%>
And in the code behind:
在后面的代码中:
ViewData["clientId"] = "ASD"; //This should be the value of item you want to select
ViewData["clients"] = clientItemList; //List<SelectListItem>
回答by CmdrTallen
Could do it pretty easy with jQuery;
用 jQuery 可以很容易地做到这一点;
$(function() {
$("#myselectlist option[@value='ItemToSelectValue'].attr('selected', 'true');
});
回答by Erik Lenaerts
I needed a dropdown in a editable grid myself with preselected dropdown values. Afaik, the selectlist data is provided by the controller to the view, so it is created before the view consumes it. Once the view consumes the SelectList, I hand it over to a custom helper that uses the standard DropDownList helper. So, a fairly light solution imo. Guess it fits in the ASP.Net MVC spirit at the time of writing; when not happy roll your own...
我自己需要一个带有预选下拉值的可编辑网格中的下拉列表。Afaik,选择列表数据由控制器提供给视图,因此它是在视图使用它之前创建的。视图使用 SelectList 后,我将其交给使用标准 DropDownList 帮助程序的自定义帮助程序。所以,一个相当轻的解决方案imo。猜测它在撰写本文时符合 ASP.Net MVC 精神;不开心的时候自己动手……
public static string DropDownListEx(this HtmlHelper helper, string name, SelectList selectList, object selectedValue) { return helper.DropDownList(name, new SelectList(selectList.Items, selectList.DataValueField, selectList.DataTextField, selectedValue)); }
回答by eudaimos
Because this is such a high result in Google, I'm providing what I found to work here (despite the age):
因为这在谷歌中的结果如此之高,我提供了我在这里找到的工作(尽管年龄):
If you are using a Strongly typed View (i.e. the Model has an assigned type), the SelectedValue provided to the Constructor of the SelectList is overwritten by the value of the object used for the Model of the page.
如果您使用的是强类型视图(即模型具有指定的类型),则提供给 SelectList 的构造函数的 SelectedValue 将被用于页面模型的对象的值覆盖。
This works well on an edit page, but not for Create when you want to preselect a specific value, so one workaround is simply to assign the correct value on a default constructed object you pass to the view as the Model. e.g.
这在编辑页面上效果很好,但当您想要预选特定值时不适用于 Create,因此一种解决方法是在您作为模型传递给视图的默认构造对象上分配正确的值。例如
var model = new SubjectViewModel()
{
Subject = new Subject(),
Types = data.SubjectTypes.ToList()
}
model.Subject.SubjectType = model.Types.FirstOrDefault(t => t.Id == typeId);
ViewData.Model = model;
return View();
so the code in my Create View that looks like this:
所以我的创建视图中的代码如下所示:
Html.DropDownListFor(model => model.Subject.SubjectTypeId, new SelectList(model.Types, "Id", "Name"))
returns the Drop Down List with the value I assigned as the SelectedValue in the list.
返回下拉列表,其中包含我在列表中指定为 SelectedValue 的值。
回答by JoeSharp
I know it' an old question, but it might help someone out there. I did what looks to be closely like what Erik did. I just created a new SelectList from my existing one...
我知道这是一个老问题,但它可能会帮助那里的人。我做了看起来很像 Erik 所做的事情。我刚刚从现有的 SelectList 中创建了一个新的 SelectList ......
SelectList myList = GetMySelectList();
SelectListItem selected = myList.FirstOrDefault(x => x.Text.ToUpper().Contains("UNITED STATES"));
if (selected != null)
{
myList = new SelectList(myList, "value", "text", selected.Value);
}
回答by spadelives
I agree with @awrigley and others that it is better to load the selected value using the selectlist constructor in the usual case when you have a single dropdownlist. However, sometimes, one needs to set the selected value on the view, such as when you have a page with n identical dropdowns. Since it is not practical to create such collections in the controller and may not even know in advance how many dropdowns you need, a better approach is to create one instance in the viewmodel as a template with no selected value set and then dynamically create the rest dynamically on the view.
我同意@awrigley 和其他人的观点,即在通常情况下,当您只有一个下拉列表时,最好使用选择列表构造函数加载所选值。但是,有时需要在视图上设置选定的值,例如当您有一个具有 n 个相同下拉列表的页面时。由于在控制器中创建这样的集合是不切实际的,甚至可能事先不知道你需要多少个下拉菜单,更好的方法是在视图模型中创建一个实例作为模板,没有选择的值集,然后动态创建其余的在视图上动态显示。
I run into this often when iterating through a list of child items on edit views when the children need dropdowns. In such cases, you can do it like this with one line of code:
当子项需要下拉列表时,我经常在编辑视图上迭代子项列表时遇到这种情况。在这种情况下,你可以用一行代码来做到这一点:
@Html.DropDownListFor(x => myViewModelFieldName, new SelectList(Model.MyRawSelectListFromMyViewModel.Select(x=> new {x.Value, x.Text}), "Value", "Text", TheValueYouWantToSelect))