问题
I am trying to create a form that will consist of a series of dropdown lists, all of which are loaded from a database. I will not know how many dropdown lists will be needed, or how many options each dropdown list will have at compile-time.
How can these fields be set-up to allow them to model-bind when posted?
There is a lot of other complexity in each of the below code elements, but I cannot get the model binding to work even when reduced down to a basic level.
The Models:
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; }
}
The Controller Get Action:
[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);
}
The Controller Post Action:
[AcceptVerbs(HttpVerbs.Post)]
[ActionName("MyAction")]
public ActionResult MyPostAction(MyPageViewModel model)
{
//Do something with posted model...
//Except 'model.ListOfDropDownLists' is always null
return View(model);
}
The View:
@model MyPageViewModel
@using (Html.BeginForm("MyPostAction"))
{
foreach (var ddl in Model.ListOfDropDownLists)
{
@Html.DropDownListFor(x => ddl.Value, ddl.Options)
}
<button type="submit">Submit</button>
}
Edit: Corrected typos and copy-paste mistakes.
Solution:
The problem turned out to be the foreach-loop within the view. Changing it into a for-loop instead caused the post to populate as expected. The updated view is below:
@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>
}
回答1:
Your view is only creating multiple select elements named dll.Value
(and duplicate ID's) which has no relationship to your model. What you need is to create elements named ListOfDropDownLists[0].Value, ListOfDropDownLists[1].Value
etc.
Change you loop in the view to this
for (int i = 0; i < Model.ListOfDropDownLists.Count; i++)
{
@Html.DropDownListFor(m => m.ListOfDropDownLists[i].Value, Model.ListOfDropDownLists[i].Options);
}
You posted code has multiple errors (e.g. your pass a model of type MyPageViewModel
but the post action method expects type of MyModel
). I assume these are just typo's.
回答2:
I can give you my solution,It is working:
Method in base controller
//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));
}
Code in controller:
DataTable dtList = new DataTable();
dtList = location.GetDistrict();
Dictionary<int, string> DistrictDictionary = GenerateDictionaryForDropDown(dtList, "Id", "DistrictName");
model.DistrictList = DistrictDictionary;
Binding Data in view:
@Html.DropDownListFor(model => model.DiscrictId, new SelectList(Model.DistrictList, "Key", "Value"), new { id = "ddlDist", @class = "form-control" })
Binding Other Dropdown from this(cascading): Other Dropdown:
@Html.DropDownListFor(model => model.TalukaId, new SelectList(Model.TalukaList, "Key", "Value"), new { id = "ddlTaluka", @class = "form-control" })
JQuery Code: $("#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);
});
Controller Method Return 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);
}
来源:https://stackoverflow.com/questions/23841504/how-do-i-model-bind-a-list-of-listselectitem-using-mvc-net