How Do I Model Bind A List Of 'List<SelectItem>' Using MVC.Net

為{幸葍}努か 提交于 2019-12-01 21:49:17

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.

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!