2016-12-02 60 views
-1

我有一個狀態下拉在我的MVC應用程序,並調用幫助器方法來填充下拉列表。在多次選擇相同的值時,下拉將重置爲默認值「選擇狀態」,而不是正確的狀態。MVC Html.DropDownListFor不綁定在選擇相同的值

HTML查看

<div> 
    @Html.LabelFor(m => m.Pat.StateId) 
    @Html.DropDownListFor(m => m.Pat.StateId, listHelper.GetState(Model.Pat.StateId)) 
    @Html.ValidationMessageFor(m => m.Pat.StateId) 
</div> 

助手代碼

 public static IList<SelectListItem> GetStateOptions(int? selectedId = null) 
     { 
      var lookupService = DependencyResolver.Current.GetService<IConstantsHelper>(); 
      var result = lookupService.GetAll<State>().Select(x => new SelectListItem 
      { 
       Value = x.Id.ToString(), 
       Text = x.Text, 
       Selected = selectedId.HasValue && selectedId == x.Id 
      }).OrderBy(x => x.Text).ToList(); 
      result.Insert(0, new SelectListItem { Value = "", Text = "Select state...", Disabled = true, Selected = result.Any(x => !x.Selected)}); 
      return result; 
     } 
+0

您可以從下拉列表中選擇它的工作原理,再向下打開下拉列表,選擇相同的項目,並將其重置爲空?你能解釋更多... – Emad

+0

**多於一次的相同值,下拉正在重置**請問您能詳細說明一下嗎? – Shyju

+0

如果你把'@(Model.Pat.StateId)'放在某處,它是否顯示你期望的值? –

回答

1

我認爲這個問題是在你的.Any條件,因爲會在你的列表中選擇非選擇,所以它會返回true。

嘗試將其更改爲:

result.Insert(0, new SelectListItem { Value = "", Text = "Select state...", Disabled = true, Selected = !result.Any(x => x.Selected)}); 
相關問題