C# MVC - 设置 SelectList 的选定值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1390830/
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
MVC - Set selected value of SelectList
提问by kaivalya
How can I set the selectedvalue property of a SelectList after it was instantiated without a selectedvalue;
在没有选择值的情况下实例化后,如何设置 SelectList 的 selectedvalue 属性;
SelectList selectList = new SelectList(items, "ID", "Name");
I need to set the selected value after this stage
我需要在此阶段之后设置选定的值
采纳答案by womp
If you have your SelectList object, just iterate through the items in it and set the "Selected" property of the item you wish.
如果您有 SelectList 对象,只需遍历其中的项目并设置您希望的项目的“Selected”属性。
foreach (var item in selectList.Items)
{
if (item.Value == selectedValue)
{
item.Selected = true;
break;
}
}
Or with Linq:
或使用 Linq:
var selected = list.Where(x => x.Value == "selectedValue").First();
selected.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 Doug Lampe
Why are you trying to set the value after you create the list? My guess is you are creating the list in your model instead of in your view. I recommend creating the underlying enumerable in your model and then using this to build the actual SelectList:
为什么要在创建列表后尝试设置值?我的猜测是您是在模型中而不是在视图中创建列表。我建议在您的模型中创建底层可枚举,然后使用它来构建实际的 SelectList:
<%= Html.DropDownListFor(m => m.SomeValue, new SelectList(Model.ListOfValues, "Value", "Text", Model.SomeValue)) %>
That way your selected value is always set just as the view is rendered and not before. Also, you don't have to put any unnecessary UI classes (i.e. SelectList) in your model and it can remain unaware of the UI.
这样你选择的值总是在视图渲染时设置,而不是在渲染之前设置。此外,您不必在模型中放置任何不必要的 UI 类(即 SelectList),并且它可以保持不知道 UI。
回答by Adam
Doug answered my question... But I'll explain what my problem was exactly, and how Doug helped me solve my problem which you could be encountering.
Doug 回答了我的问题...但我会解释我的问题究竟是什么,以及 Doug 如何帮助我解决您可能遇到的问题。
I call jquery $.post
and am replacing my div with my partial view, like so.
我调用 jquery$.post
并用我的部分视图替换我的 div,就像这样。
function AddNewAddress (paramvalue) {
$.post(url, { param: paramvalue}, function(d) {
$('#myDiv').replaceWith(d);
});
}
When doing so, for some reason when stepping into my model my selected value affiliated property was never set, only until I stepped into the view it came into scope.
这样做时,出于某种原因,当我进入我的模型时,从未设置我选择的值附属属性,直到我进入它进入范围的视图。
So, What I had before
所以,我之前所拥有的
@Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, Model.CustomerAddresses[i].YearsAtAddressSelectList, new {onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")"})
however even though Model.CustomerAddresses[i].YearsAtAddressSelectList, was set... it didn't set the selected value.
然而,即使 Model.CustomerAddresses[i].YearsAtAddressSelectList, 被设置......它也没有设置选定的值。
So after....
所以之后……
@Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, new SelectList(Model.CustomerAddresses[i].YearsAtAddressSelectList, "Value", "Text", Model.CustomerAddresses[i].YearsAtAddress), new { onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")" })
and it worked!
它奏效了!
I decided not to use DropDownListFor
as it has problem when using unobtrusive validation, which is why i reference the following if your curious in a class classed
我决定不使用,DropDownListFor
因为它在使用不显眼的验证时有问题,这就是为什么如果您对分类的类感到好奇,我会参考以下内容
HtmlExtensions.cs
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)
{
return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, null /* htmlAttributes */);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes)
{
return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, new RouteValueDictionary(htmlAttributes));
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)
{
return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, htmlAttributes);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel)
{
return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, optionLabel, null /* htmlAttributes */);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes)
{
return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, optionLabel, new RouteValueDictionary(htmlAttributes));
}
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Users cannot use anonymous methods with the LambdaExpression type")]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
{
if (expression == null)
{
throw new ArgumentNullException("expression");
}
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
IDictionary<string, object> validationAttributes = htmlHelper
.GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata);
if (htmlAttributes == null)
htmlAttributes = validationAttributes;
else
htmlAttributes = htmlAttributes.Concat(validationAttributes).ToDictionary(k => k.Key, v => v.Value);
return SelectExtensions.DropDownListFor(htmlHelper, expression, selectList, optionLabel, htmlAttributes);
}
回答by Immortal Blue
Further to @Womp answer, it's worth noting that the "Where" Can be dropped, and the predicate can be put into the "First" call directly, like this:
进一步@Womp 回答,值得注意的是“Where”可以被删除,并且谓词可以直接放入“First”调用中,如下所示:
list.First(x => x.Value == "selectedValue").Selected = true;
list.First(x => x.Value == "selectedValue").Selected = true;
回答by Alex Stephens
A bit late to the party here but here's how simple this is:
这里的聚会有点晚了,但这是多么简单:
ViewBag.Countries = new SelectList(countries.GetCountries(), "id", "countryName", "82");
this uses my method getcountries to populate a model called countries, obviousley you would replace this with whatever your datasource is, a model etc, then sets the id as the value in the selectlist. then just add the last param, in this case "82" to select the default selected item.
这使用我的方法 getcountries 来填充一个名为国家的模型,很明显,您可以将其替换为您的数据源、模型等,然后将 id 设置为选择列表中的值。然后只需添加最后一个参数,在本例中为“82”以选择默认选定项。
[edit] Here's how to use this in Razor:
[编辑] 以下是在 Razor 中使用它的方法:
@Html.DropDownListFor(model => model.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries, new { @class = "form-control" })
Important:Also, 1 other thing to watch out for, Make sure the model field that you use to store the selected Id (in this case model.CountryId) from the dropdown list is nullable and is set to null on the first page load. This one gets me every time.
重要提示:另外,还有一件事需要注意,请确保用于存储下拉列表中所选 Id(在本例中为 model.CountryId)的模型字段可以为空,并且在第一次加载页面时设置为空。这个每次都让我着迷。
Hope this saves someone some time.
希望这可以节省一些时间。
回答by mca
You can use below method, which is quite simple.
您可以使用以下方法,这很简单。
new SelectList(items, "ID", "Name",items.Select(x=> x.Id).FirstOrDefault());
This will auto-select the first item in your list. You can modify the above query by adding a where clause.
这将自动选择列表中的第一项。您可以通过添加 where 子句来修改上述查询。
回答by Franchesco
I usually use this method
我通常使用这种方法
public static SelectList SetSelectedValue(SelectList list, string value)
{
if (value != null)
{
var selected = list.Where(x => x.Value == value).First();
selected.Selected = true;
return list;
}
return list;
}
回答by mzonerz
Simply use the third parameter for selected value in mvc4
只需将第三个参数用于 mvc4 中的选定值
@Html.DropDownList("CountryList", new SelectList(ViewBag.Countries, "Value", "Text","974"))
Here "974" is selected Value Specified
这里选择“974” 指定值
In my result selected country is now qatar.in C# as below`
在我的结果中选择的国家现在是 qatar.in C# 如下`
foreach (CountryModel item in CountryModel.GetCountryList())
{
if (item.CountryPhoneCode.Trim() != "974")
{
countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode });
}
else {
countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true });
}
}
回答by Adrian Hedley
I wanted the dropdown to select the matching value of the id in the action method. The trick is to set the Selected property when creating the SelectListItem Collection. It would not work any other way, perhaps I missed something but in end, it is more elegant in my option.
我希望下拉列表在操作方法中选择 id 的匹配值。诀窍是在创建 SelectListItem 集合时设置 Selected 属性。它不会以任何其他方式工作,也许我错过了一些东西,但最终,我的选择更优雅。
You can write any method that returns a boolean to set the Selected value based on your requirements, in my case I used the existing Equal Method
您可以编写任何返回布尔值的方法,以根据您的要求设置 Selected 值,在我的情况下,我使用了现有的 Equal 方法
public ActionResult History(long id)
{
var app = new AppLogic();
var historyVM = new ActivityHistoryViewModel();
historyVM.ProcessHistory = app.GetActivity(id);
historyVM.Process = app.GetProcess(id);
var processlist = app.GetProcessList();
historyVM.ProcessList = from process in processlist
select new SelectListItem
{
Text = process.ProcessName,
Value = process.ID.ToString(),
Selected = long.Equals(process.ID, id)
};
var listitems = new List<SelectListItem>();
return View(historyVM);
}