使用基于另一个ComboBox选择的Javascript填充MVC 5查看ComboBox

时间:2017-03-27 12:54:03

标签: javascript c# jquery asp.net-mvc combobox

我正在开发一个ASP.NET Core MVC Web项目,我希望根据使用JavaScript(Json)选择ComboBox A(Stations)来填充ComboBox B(Churches)的值。我试图研究没有成功。 这是我的代码:

MVC查看代码:

 <div class="form-group">
                <label asp-for="RSTATIONID" class="col-sm-4 control-label">Station:</label>
                <div id="station" class="col-sm-8">
                    <select asp-for="RSTATIONID" class="form-control" asp-items="ViewBag.RSTATIONID"
                            onchange="LoadChurches(this)"></select>
                    <span asp-validation-for="RSTATIONID" class="text-danger" />
                </div>
            </div>
            <div class="form-group">
                <label asp-for="RCHURCHID" class="col-sm-4 control-label">Church:</label>
                <div id="church" class="col-sm-8">
                    <select asp-for="RCHURCHID" class="form-control" asp-items="ViewBag.RCHURCHID"></select>
                    <span asp-validation-for="RCHURCHID" class="text-danger" />
                </div>
            </div>

JavaScript代码:

function LoadChurches(e) {
    var stationID = e.value;
    //alert(stationID);
    $.ajax
   ({
       url: '/CaptureReceipts/LoadChurches',
       type: 'POST',
       datatype: 'application/json',
       contentType: 'application/json',
       data: JSON.stringify({
           stationID: +stationID
       }),
       success: function (result) {
           var res = result.value;
           alert(JSON.stringify(res));
           /*$("#church").html("");
           $.each($.parseJSON(result), function (i, church) {
               SetSel(this);
           }); */
       },
       error: function () {
           alert("Churches can not load"); 
       } 
   });
}

控制器代码:

 public JsonResult LoadChurches(string statID)
    {
        int stationID = Convert.ToInt32(statID);
        var churches = new SelectList(_context.v_Church.Where(m => m.StationID == stationID), "ID", "churchName");                    
        return Json(ViewData);
    } 

Controller名称是CaptureReceiptsController。请帮我知道可能出现的问题。

1 个答案:

答案 0 :(得分:0)

在控制器中返回简单的json数组:

var churches = _context.v_Church
                  .Where(m => m.StationID == stationID)
                  .Select(x => new {id = x.ID, name = x.churchName })
                  .ToArray();
return JSON(churches);

success回调中:

success: function (data) {
    var churchSelect = $("#church > select")
    churchSelect.html(""); //clear select
    for (var i =0;i<data.length;i++){
        var opt = document.createElement('option');
        opt.innerHTML = data[i].name;
        opt.value = data[i].id;
        churchSelect.append(opt);
    }
}