AJAX级联下拉列表ASP.NET MVC

时间:2018-05-24 04:17:08

标签: c# ajax asp.net-mvc

我正在处理工作申请表。该请求涉及一系列产品。有很多系列,所以我试图通过它们产生的产品线来过滤它们。我正在尝试使用来自Ajax的级联下拉列表。我知道脚本在某种程度上有效,因为默认选择的选项更改为" Make Selection"。但是,下拉列表的其余部分不会填充。

以下是两个下拉列表。

@Html.DropDownListFor(model => model.SelectedProductLine, new SelectList(Model.ProductLines, "Value", "Text"), "Select a Product Line", new { @class = "form-control", @style = "width: 400px;", @id = "ProductLineID"})

@Html.DropDownListFor(model => model.SelectedSeries, new SelectList(string.Empty, "Value", "Text"), "Select a Series", new { @class = "form-control", @id = "SeriesID"})

Ajax脚本。     

$(document).ready(function () {
    //Dropdownlist Selectedchange event
    $('#ProductLineID').change(function () {

        $.ajax({
            url: '/SMRMaster/RequestForm/GetSeries',
            type: 'GET',
            datatype: 'JSON',
            data: { id: $('#ProductLineID').val() },
            success: function (result) {
                $('#SeriesID').html('');
                $('#SeriesID').append($('<option>Make Selection</option>'));
                $.each(result, function (index, item) {
                    $('#SeriesID').append($('<option></option>').val(item.Value).html(item.Text));
                });
            }
        });
    });
});

控制器。

public JsonResult GetSeries(string id)
    {
        int Id = Convert.ToInt32(id);
        db.Database.ExecuteSqlCommand("SET TRANSACTION ISOLATION LEVEL READ UNOCMMITTED;");
        var productLineName = "";
        switch (Id)
        {
            case 0:
                productLineName = "Electric";
                break;
            case 1:
                productLineName = "Europe Gas";
                break;
            case 2:
                productLineName = "Gas";
                break;
            case 3:
                productLineName = "Miscellaneous";
                break;
            case 4:
                productLineName = "Water";
                break;
            default:
                productLineName = "Electric";
                break;
        }
        IEnumerable<SelectListItem> series = (from s in db.Series
                      where s.ProductLineName == productLineName
                      select new SelectListItem { Value = s.ProductLineName, Text = s.ProductLineName }).ToList();


        return Json(series, JsonRequestBehavior.AllowGet);
    }

    public List<ProductLine> GetProductLines()
    {
        db.Database.ExecuteSqlCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
        var productLineList = (from p in db.ProductLines
                               select p).ToList();

        return productLineList;
    }


    public ActionResult RequestForm()
    {
        var count = 0;
        var productLineList = new List<SelectListItem>();
        foreach (var item in GetProductLines())
        {
            productLineList.Add(new SelectListItem { Text = item.ProductlineName, Value = count.ToString() });

        }
        db.Database.ExecuteSqlCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
        var requestViewModel = new RequestViewModel { SMRMaster = new SMRMaster(), Engineers = GetEngineers(), ProductLines = productLineList };
        return View(requestViewModel);
    }

和视图模型。

public class RequestViewModel
{
    public List<SelectListItem> ProductLines { get; set; }
    public string SelectedProductLine { get; set; }
    public SMRMaster SMRMaster { get; set; }
    public List<string> Engineers { get; set; }
    [Required(ErrorMessage = "Engineer is required.")]
    public string SelectedEngineer { get; set; }
    public List<Series> Series { get; set; } 
    public string SelectedSeries { get; set; }
}

我不知道错误的来源。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

试试这个

$.each(result, function (i, item) {
          var optionData = '<option value="' + item.Value + '">' + obj.Text + '</option>';
             $(optionData).appendTo('#SeriesID')      
});

或调试并查看您对服务器的响应。

答案 1 :(得分:0)

一位同事帮助我解决了这个问题。首先,Ajax脚本使用了错误的URL。其次,我的控制器功能不必要地复杂化。

这是更新的AJAX脚本:     

$(document).ready(function () {
    //Dropdownlist Selectedchange event
    $('#ProductLine').change(function () {
        $.ajax({
            url: '/SMRMaster/GetSeries',
            type: 'GET',
            datatype: 'JSON',
            data: { productLine: $('#ProductLine').val() },
            success: function (result) {
                $('#SeriesID').html('');
                $('#SeriesID').append($('<option>Make Selection</option>'));
                $.each(result, function (i, item) {
                    var optionData = '<option value="' + item.Value + '">' + item.Text + '</option>';
                    $(optionData).appendTo('#SeriesID')
                });
            }
        });
    });
});

这是更新的控制器:

    public JsonResult GetSeries(string productLine)
    {
        db.Database.ExecuteSqlCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
        List<SelectListItem> series = (from s in db.Series
                                        where s.ProductLineName == productLine
                                        select new SelectListItem { Value = s.SeriesName, Text = s.SeriesName }).Distinct().ToList();
        return Json(series, JsonRequestBehavior.AllowGet);
    }

    public List<ProductLine> GetProductLines()
    {
        db.Database.ExecuteSqlCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
        var productLineList = (from p in db.ProductLines
                               select p).ToList();
        return productLineList;
    }


    public ActionResult RequestForm()
    {
        var productLineList = new List<SelectListItem>();
        foreach (var item in GetProductLines())
        {
            productLineList.Add(new SelectListItem { Text = item.ProductlineName, Value = item.ProductlineName });
        }
        db.Database.ExecuteSqlCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
        var requestViewModel = new RequestViewModel { SMRMaster = new SMRMaster(), Engineers = GetEngineers(), ProductLines = productLineList };
        return View(requestViewModel);
    }