![](/img/trans.png)
[英]How to bind a model in mvc.net where the model contains a list of dropdowns?
[英]How Do I Model Bind A List Of 'List<SelectItem>' Using 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);
}
控制器發布動作:
[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循環會導致帖子按預期填充。 更新后的視圖如下:
@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>
}
您的視圖僅創建多個名為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 action方法需要MyModel
類型)。 我認為這些只是錯字。
我可以給你我的解決方案,它的工作原理是:
基本控制器中的方法
//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”)。change(function(){var TalukaList =“Select”$('#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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.