简体   繁体   English

AJAX级联下拉列表ASP.NET MVC

[英]AJAX Cascading Dropdowns ASP.NET MVC

I am working on a request form for work. 我正在准备工作申请表。 The request deals with series of products. 该请求涉及产品系列。 There are many series, so I am trying to filter them down by the product line that they are produced on. 有很多系列,所以我试图按生产它们的产品系列过滤掉它们。 I am attempting this using cascading dropdown lists from Ajax. 我正在尝试使用来自Ajax的级联下拉列表。 I know the script is working to a degree, because the default selected option changes to "Make Selection". 我知道脚本在一定程度上可以正常工作,因为默认的选定选项更改为“进行选择”。 However, the rest of the dropdown does not populate. 但是,其余的下拉列表不会填充。

Here are the two dropdowns. 这是两个下拉菜单。

@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"})

The Ajax Script. 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));
                });
            }
        });
    });
});

The Controller. 控制器。

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);
    }

And the view model. 和视图模型。

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; }
}

I do not know where the error is coming from. 我不知道错误是从哪里来的。 Any help is appreciated. 任何帮助表示赞赏。

Try this 尝试这个

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

Or debug and see what's your response from server. 或调试并查看您对服务器的响应。

A colleague helped me solve this problem. 一位同事帮助我解决了这个问题。 Firstly, the Ajax script was using the wrong URL. 首先,Ajax脚本使用了错误的URL。 Secondly, my controller functions were unnecessarily complicated. 其次,我的控制器功能不必要地复杂。

Here is the updated AJAX script: 这是更新的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')
                });
            }
        });
    });
});

And here is the updated Controller: 这是更新的控制器:

    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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM