[英]MVC - Set selected value of SelectList
在沒有選擇值的情況下實例化后,如何設置 SelectList 的 selectedvalue 屬性;
SelectList selectList = new SelectList(items, "ID", "Name");
我需要在此階段之后設置選定的值
如果您有 SelectList 對象,只需遍歷其中的項目並設置您希望的項目的“Selected”屬性。
foreach (var item in selectList.Items)
{
if (item.Value == selectedValue)
{
item.Selected = true;
break;
}
}
或使用 Linq:
var selected = list.Where(x => x.Value == "selectedValue").First();
selected.Selected = true;
這里的聚會有點晚了,但這是多么簡單:
ViewBag.Countries = new SelectList(countries.GetCountries(), "id", "countryName", "82");
這使用我的方法 getcountries 來填充一個名為國家的模型,很明顯,您可以將其替換為任何數據源、模型等,然后將 id 設置為選擇列表中的值。 然后只需添加最后一個參數,在本例中為“82”以選擇默認選定項。
[編輯] 以下是在 Razor 中使用它的方法:
@Html.DropDownListFor(model => model.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries, new { @class = "form-control" })
重要提示:另外,還有一件事需要注意,請確保用於存儲下拉列表中所選 Id(在本例中為 model.CountryId)的模型字段可以為空,並且在第一次加載頁面時設置為空。 這個每次都讓我着迷。
希望這可以節省一些時間。
只需將第三個參數用於 mvc4 中的選定值
@Html.DropDownList("CountryList", new SelectList(ViewBag.Countries, "Value", "Text","974"))
這里選擇“974” 指定值
在我的結果中選擇的國家現在是 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 });
}
}
為什么要在創建列表后嘗試設置值? 我的猜測是您是在模型中而不是在視圖中創建列表。 我建議在您的模型中創建底層可枚舉,然后使用它來構建實際的 SelectList:
<%= Html.DropDownListFor(m => m.SomeValue, new SelectList(Model.ListOfValues, "Value", "Text", Model.SomeValue)) %>
這樣你選擇的值總是在視圖渲染時設置,而不是在渲染之前設置。 此外,您不必在模型中放置任何不必要的 UI 類(即 SelectList),並且它可以保持不知道 UI。
對於@Womp 的回答,值得注意的是,可以刪除“Where”,並且可以將謂詞直接放入“First”調用中,如下所示:
list.First(x => x.Value == "selectedValue").Selected = true;
Doug 回答了我的問題...但我會解釋我的問題究竟是什么,以及 Doug 如何幫助我解決您可能遇到的問題。
我調用 jquery $.post
並用我的部分視圖替換我的 div,就像這樣。
function AddNewAddress (paramvalue) {
$.post(url, { param: paramvalue}, function(d) {
$('#myDiv').replaceWith(d);
});
}
這樣做時,出於某種原因,當我進入我的模型時,從未設置我選擇的值附屬屬性,直到我進入它進入范圍的視圖。
所以,我之前所擁有的
@Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, Model.CustomerAddresses[i].YearsAtAddressSelectList, new {onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")"})
然而,即使 Model.CustomerAddresses[i].YearsAtAddressSelectList, 被設置......它也沒有設置選定的值。
所以之后……
@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 + ")" })
它奏效了!
我決定不使用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);
}
您可以使用以下方法,這很簡單。
new SelectList(items, "ID", "Name",items.Select(x=> x.Id).FirstOrDefault());
這將自動選擇列表中的第一項。 您可以通過添加 where 子句來修改上述查詢。
我在這里結束是因為 SelectListItem 不再正確選擇選定的值。 為了修復它,我將 EditorFor 的用法更改為“手動”方法:
<select id="Role" class="form-control">
@foreach (var role in ViewBag.Roles)
{
if (Model.Roles.First().RoleId == role.Value)
{
<option value="@role.Value" selected>@role.Text</option>
}
else
{
<option value="@role.Value">@role.Text</option>
}
}
</select>
希望它可以幫助某人。
我自己需要一個帶有預選下拉值的可編輯網格中的下拉列表。 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)); }
我通常使用這種方法
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;
}
我希望下拉列表在操作方法中選擇 id 的匹配值。 訣竅是在創建 SelectListItem 集合時設置 Selected 屬性。 它不會以任何其他方式工作,也許我錯過了一些東西,但最終,我的選擇更優雅。
您可以編寫任何返回布爾值的方法,以根據您的要求設置 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);
}
下面的代碼解決了兩個問題:1)動態設置下拉列表的選定值,2)更重要的是為模型中的索引數組創建一個下拉列表。 這里的問題是每個人都使用選擇列表的一個實例,即 ViewBoag.List,而數組需要每個下拉列表的一個 Selectlist 實例才能設置所選值。
在控制器中將 ViewBag 變量創建為 List(不是 SelectList)
//控制器代碼
ViewBag.Role = db.LUT_Role.ToList();
//在視圖中@Html.DropDownListFor(m => m.Contacts[i].Role, new SelectList(ViewBag.Role,"ID","Role",Model.Contacts[i].Role))
如果有人在看我重新發布我的答案: SelectListItem selected = true not working in view
在我自己尋找這個問題的答案之后 - 我一路上得到了一些提示,但這就是我的最終解決方案。 它是一個擴展方法。 我正在使用 MVC 5 C# 4.52 是目標。 下面的代碼將選擇設置為列表中的第一項,因為這是我需要的,您可能只想傳遞一個字符串並跳過枚舉 - 但我也想確保我有一些東西從數據庫返回到我的 SelectList)
Extension Method:
公共靜態類 SelectListextensions {
public static System.Web.Mvc.SelectList SetSelectedValue
(這個 System.Web.Mvc.SelectList 列表,字符串值) { if (value != null) { var selected = list.Where(x => x.Text == value).FirstOrDefault(); selected.Selected = true;
} 返回列表; }
}
對於那些喜歡完全低調的人(像我一樣),這里是用法。 對象類別有一個定義為名稱的字段 - 該字段將在下拉列表中顯示為文本。 您可以在上面的代碼中看到對 Text 屬性的測試。
Example Code:
SelectList categorylist = new SelectList(dbContext.Categories, "Id", "Name");
SetSelectedItemValue(categorylist);
select list function:
private SelectList SetSelectedItemValue(SelectList source) { Category category = new Category();
SelectListItem firstItem = new SelectListItem();
int selectListCount = -1;
if (source != null && source.Items != null)
{
System.Collections.IEnumerator cenum = source.Items.GetEnumerator();
while (cenum.MoveNext())
{
if (selectListCount == -1)
{
selectListCount = 0;
}
selectListCount += 1;
category = (Category)cenum.Current;
source.SetSelectedValue(category.Name);
break;
}
if (selectListCount > 0)
{
foreach (SelectListItem item in source.Items)
{
if (item.Value == cenum.Current.ToString())
{
item.Selected = true;
break;
}
}
}
}
return source;
}
你可以把它變成一個通用的全包函數/擴展——但它對我來說是正常的
使用 LINQ 並在“選定”上添加條件作為問號條件。
var listSiteId = (from site in db.GetSiteId().ToList()
select new SelectListItem
{
Value = site.SITEID,
Text = site.NAME,
Selected = (dimension.DISPLAYVALUE == site.SITEID) ? true : false,
}).ToList();
ViewBag.SiteId = listSiteId;
我認為這是所有“前端”DDL 代碼(都在帶有實體框架的 .NET MVC 中的 CSHTML 頁面中——因此“Id”數據庫引用,以及帶有 jQuery 前端驗證的 Bootstrap 3 樣式)。 我也提到“前端”,因為我沒有顯示任何模型注釋或控制器/存儲庫/服務代碼。
它在 db 表中有一個默認值(“不適用”或 Id #4),這很煩人,但我不得不在現實世界中處理這個問題,所以希望這個例子有幫助。 我在這個頁面上的原因是為了解決這樣的情況,一旦我想起了如何去做,我想我會在這里發布我所做的以防對其他人有幫助,因為其他答案不是正是這樣。
好的,這是在“創建”表單上執行的操作,您將在其中創建初始對象。 這就是為什么默認選擇是 db 表中的 #4。
<div class="form-group">
@Html.LabelFor(
m => m.Survey.CountryId,
"North American Country you live in?", new
@* .required is custom CSS class to add red asterisk after label *@
{ @class = "col-md-4 control-label required" }
)
<div class="col-md-8">
@Html.DropDownListFor(
m => m.Survey.CountryId,
Model.Surveys.Select(i => new SelectListItem()
{
Value = i.Id.ToString(),
Text = $"{i.Code} - {i.Description}",
/* gave default selection of Id #4 in db table */
Selected = i.Id == 4 ? true : false
}), new
{
@class = "form-control",
data_val = "true",
data_val_required = "This is a required selection"
})
@Html.ValidationMessageFor(m => m.Survey.CountryId)
</div>
</div>
<div class="col-md-8">
@Html.DropDownListFor(
m => m.Survey.CountryId,
Model.Surveys.Select(i => new SelectListItem()
{
Value = i.Id.ToString(),
Text = $"{i.Code} - {i.Description}",
/* for Edit form, find the actual selected value the survey taker made */
Selected = i.Id == Model.Survey.CountryId ? true : false
}), new
{
@class = "form-control",
data_val = "true",
data_val_required = "This is a required selection"
})
@Html.ValidationMessageFor(m => m.Survey.CountryId)
</div>
@Html.DropDownListFor(
m => m.Survey.CountryId,
Model.Surveys.Select(i => new SelectListItem()
{
Value = i.Id.ToString(),
Text = $"{i.Code} - {i.Description}",
Selected = i.Id == Model.Survey.CountryId ? true : false
/* Add a default DDL selection when you're not trying to get it from a db */
}), "-- select a country --", new
{
@class = "form-control"
})
此 DDL 用於“州”而不是“國家”,它有一個默認的“--選擇--”選項,但更像是“編輯表單”版本,因為它已經被選中,現在顯示從數據庫中檢索到的選項.
但除此之外...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.