2014-05-24 14 views
3

我想創建一個表格,將包含一系列下拉列表,所有這些都從數據庫中加載。我不知道需要多少下拉列表,或者每個下拉列表在編譯時會有多少個選項。我如何建模綁定列表'<SelectItem>'使用MVC.Net

這些字段如何設置以允許它們在發佈時建模?

下面的每個代碼元素都有很多其他複雜性,但即使降低到基本級別,我也無法使模型綁定正常工作。


型號:

public class MyPageViewModel 
{ 
    public List<MyDropDownListModel> ListOfDropDownLists { get; set; } 
} 

public class MyDropDownListModel 
{ 
    public string Key { get; set; } 
    public string Value { get; set; } 
    public List<SelectListItem> Options { get; set; } 
} 

的控制器獲取操作:

[AcceptVerbs(HttpVerbs.Get)] 
[ActionName("MyAction")] 
public ActionResult MyGetAction() 
{ 
    var values_1 = new List<string> {"Val1", "Val2", "Val3"}; 
    var options_1 = 
     values_1 
      .ConvertAll(x => new SelectListItem{Text=x,Value=x}); 

    var myDropDownListModel_1 = 
     new MyDropDownListModel { Key = "Key_1", Options = options_1 }; 


    var values_2 = new List<string> {"Val4", "Val5", "Val6"}; 
    var options_2 = 
     values_2 
      .ConvertAll(x => new SelectListItem{Text=x,Value=x})}; 

    var myDropDownListModel_2 = 
     new MyDropDownListModel { Key = "Key_2", Options = options_2 }; 


    var model = 
     new MyPageViewModel 
     { 
      ListOfDropDownLists = 
       new List<MyDropDownListModel> 
       { 
        myDropDownListModel_1, 
        myDropDownListModel_2, 
       } 
     }; 

    return View(model); 
} 

的控制器POST操作:

[AcceptVerbs(HttpVerbs.Post)] 
[ActionName("MyAction")] 
public ActionResult MyPostAction(MyPageViewModel model) 
{ 
    //Do something with posted model... 
    //Except 'model.ListOfDropDownLists' is always null 

    return View(model); 
} 

的觀點:

@model MyPageViewModel 

@using (Html.BeginForm("MyPostAction")) 
{ 
    foreach (var ddl in Model.ListOfDropDownLists) 
    { 
     @Html.DropDownListFor(x => ddl.Value, ddl.Options) 
    } 
    <button type="submit">Submit</button> 
} 

編輯:更正了拼寫錯誤和複製粘貼錯誤。


問題被證明是在視圖中在foreach環。將其更改爲for-loop會導致帖子按預期填充。更新的觀點是如下:

@using (Html.BeginForm("MyPostAction")) 
{ 
    for (int i = 0; i < Model.ListOfDropDownLists.Count; i++) 
{ 
     @Html.HiddenFor(x => x.ListOfDropDownLists[i].Key) 
     @Html.DropDownListFor(m => m.ListOfDropDownLists[i].Value, Model.ListOfDropDownLists[i].Options); 
    } 
    <button type="submit">Submit</button> 
} 
+0

你有什麼錯誤嗎? –

+0

@ user256103不會發生錯誤。當我在post操作中的斷點處調試時,模型屬性「MyPageViewModel.ListOfDropDownLists」爲null。 – Gifreakius

回答

2

您的視圖只創建一個名爲dll.Value多個選擇元件(以及重複的ID),其中有你的模型沒有任何關係。你需要的是創建一個名爲ListOfDropDownLists[0].Value, ListOfDropDownLists[1].Value

更改您在循環視圖這個

for (int i = 0; i < Model.ListOfDropDownLists.Count; i++) 
{  
    @Html.DropDownListFor(m => m.ListOfDropDownLists[i].Value, Model.ListOfDropDownLists[i].Options); 
} 

你貼的代碼元素中有多處錯誤(例如,您的通MyPageViewModel類型的模型,但POST操作方法預計類型MyModel)。我認爲這些只是錯字。

+0

這是對的錢。我還加了一個隱藏字段,以便將帖子返回給Key。 – Gifreakius

0

我可以給你我的解決方案,它的工作:

方法基本控制器

//To bind Dropdown list 
    protected Dictionary<int, string> GenerateDictionaryForDropDown(DataTable dtSource, string keyColumnName, string valueColumnName) 
    { 
     return dtSource.AsEnumerable() 
      .ToDictionary<DataRow, int, string>(row => row.Field<int>(keyColumnName), 
            row => row.Field<string>(valueColumnName)); 
    } 

守則控制器:

DataTable dtList = new DataTable(); 

    dtList = location.GetDistrict(); 
    Dictionary<int, string> DistrictDictionary = GenerateDictionaryForDropDown(dtList, "Id", "DistrictName"); 
    model.DistrictList = DistrictDictionary; 

綁定數據:

@Html.DropDownListFor(model => model.DiscrictId, new SelectList(Model.DistrictList, "Key", "Value"), new { id = "ddlDist", @class = "form-control" }) 

綁定其他下拉從這裏(級聯): 其他下拉:

@Html.DropDownListFor(model => model.TalukaId, new SelectList(Model.TalukaList, "Key", "Value"), new { id = "ddlTaluka", @class = "form-control" }) 

jQuery代碼: $( 「#ddlDist」)變化(函數(){ VAR TalukaList = 「選擇」 $('#ddlTaluka')。html(TalukaList);

 $.ajax({ 
      type: "Post", 
      dataType: 'json', 
      url: 'GetTaluka', 
      data: { "DistId": $('#ddlDist').val() }, 
      async: false, 
      success: function (data) { 
       $.each(data, function (index, optionData) { 
        TalukaList = TalukaList + "<option value='" + optionData.Key + "'>" + optionData.Value + "</option>"; 
       }); 
      }, 
      error: function (xhr, status, error) { 
       //alert(error); 
      } 
     }); 
     $('#ddlTaluka').html(TalukaList); 
    }); 

控制器方法返回JSON

public JsonResult GetTaluka(int DistId) 
{ 
    LocationDH location = new LocationDH(); 
    DataTable dtTaluka = location.GetTaluka(DistId); 
    Dictionary<int, string> DictionaryTaluka = GenerateDictionaryForDropDown(dtTaluka, "ID", "TalukaName"); 
    return Json(DictionaryTaluka.ToList(), JsonRequestBehavior.AllowGet); 
} 
+0

我不太明白這是否適合這個問題。視圖代碼將導致只有一個下拉菜單,是否正確?我遇到的模型綁定問題發生在同一個表單中發佈多個下拉列表時。 – Gifreakius

+0

你想級聯drowdowns? –