2009-09-07 58 views
45

如何設置選擇列表的selectedvalue屬性後,它實例化沒有selectedvalue;MVC - 設置選擇列表的選定值

SelectList selectList = new SelectList(items, "ID", "Name"); 

我需要這個階段

+0

見我DDL教程的http://www.asp。 net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc和http://blogs.msdn.com/b/rickandy/ archive/2012/01/09/cascasding-dropdownlist-in-asp-net-mvc.aspx – RickAndMSFT 2012-02-14 19:22:46

+0

我找到了解決此問題的報告[此處] [1]。 [1]:http://stackoverflow.com/a/11705380/277900 – ararog 2012-07-31 12:21:24

+0

跑進同一個問題。當天結束時,我只做了一次Razor IF,如果disabled被禁用了,那麼這個禁用代碼的行會被複制,但同樣的行會被複制,但不會被禁止編碼。它不簡潔 - 但它易於閱讀和遵循其他開發人員。 – ppumkin 2013-06-05 09:48:46

回答

60

後集中選定的值。如果你有你的SelectList對象,只是通過它的項目進行迭代,並設置想要的項目「選定」屬性。

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; 
+0

謝謝,我將標記爲答案,如果沒有其他解決方案 - 我期待有一個內置的方式來設置它,而不是迭代的項目 – kaivalya 2009-09-07 20:39:43

+3

SelectList的SelectedValue屬性是隻讀的,因爲沒有唯一性的保證。就我所知,你真的必須在項目級別處理它。 – womp 2009-09-07 20:55:04

+4

這兩個選項都不適用於MVC3迭代選項:不起作用b/c item.Value不存在。 Linq選項:單個項目設置成功,但列表忽略更新。 – Har 2012-03-16 13:50:16

2

我在編輯網格需要一個下拉自己與預選的下拉值。 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)); 
} 
8

爲什麼你想創建列表後設置值?我的猜測是你正在模型中創建列表,而不是在你的視圖中。我建議您在模型中創建的基本枚舉,然後用它來構建實際的SelectList:

<%= Html.DropDownListFor(m => m.SomeValue, new SelectList(Model.ListOfValues, "Value", "Text", Model.SomeValue)) %> 

這樣,你選擇的值總是設置同樣的觀點被渲染而不是之前。此外,您不必在模型中放置任何不必要的UI類(即SelectList),並且可以不知道UI。

+7

你有沒有爲真實的工作?當我使用這種方法時,它會生成下拉列表的html,但不會根據SelectList構造函數的最後一個參數設置所選值。 – 2012-12-28 10:10:54

+2

這種方法對我來說也不適用。 – 2013-06-06 00:47:26

+9

當使用強類型'For'版本的'Html.DropDownList'時,'SelectList'構造函數中的「當前選定值」被忽略。做得不錯,雖然得到6票不正確的答案:) – 2013-08-05 10:55:50

2

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); 

} 
3

繼@Womp的答案,這是值得注意的該「去哪兒」可以下降,謂語可以放入「第一」直接調用,就像這樣:

list.First(x => x.Value == "selectedValue").Selected = true;

+0

對於downvoter - 你能否解釋爲什麼覺得這是一個不好的答案?! – 2016-05-20 07:46:22

15

有點晚了這裏的黨,但這裏是如何SIMP樂是這樣的:

ViewBag.Countries = new SelectList(countries.GetCountries(), "id", "countryName", "82"); 

這種使用我的方法的getCountries填充一個模式叫國家,obviousley你會以您的數據源是替換此,模型等,然後設置ID在選擇列表的價值。那麼只需添加最後一個參數,在本例中選擇「82」來選擇默認的選定項目。

[編輯] 下面介紹如何在剃刀使用:

@Html.DropDownListFor(model => model.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries, new { @class = "form-control" }) 

希望這樣可以節省別人一些時間。

+5

原帖發表「如何在實例化後設置值」。這並沒有回答這個問題。 – 2015-06-05 09:08:41

1

你可以使用下面的方法,這很簡單。

new SelectList(items, "ID", "Name",items.Select(x=> x.Id).FirstOrDefault()); 

這會自動選擇列表中的第一項。您可以通過添加where子句來修改上述查詢。

+1

OP在實例化列表後詢問如何設置選擇*。 – ProfK 2015-05-07 08:42:27

1

我通常使用這種方法

 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; 
    } 
7

在mvc4只需使用第三個參數的選定值

@Html.DropDownList("CountryList", new SelectList(ViewBag.Countries, "Value", "Text","974")) 

這裏的「974」被選擇數值指定

在我的結果選定的國家現在是卡塔爾在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 }); 

      } 
     } 
+0

我想我必須將ViewBag項目轉換爲IEnumerable項目,但這項工作完美無缺。 – 2017-11-07 15:10:06

0

我希望下拉菜單在操作方法中選擇id的匹配值。訣竅是在創建SelectListItem集合時設置Selected屬性。它不會以任何其他方式工作,也許我錯過了一些東西,但最終,我的選擇更優雅。

您可以編寫返回一個布爾值來設定根據您的要求選擇的值的任何方法,在我的情況下,我利用了現有的平等法

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); 
     }