AJAX级联下拉列表ASP.NET MVC [英] AJAX Cascading Dropdowns ASP.NET MVC

查看:91
本文介绍了AJAX级联下拉列表ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一份工作申请表.该请求涉及产品系列.有很多系列,所以我试图按生产它们的产品系列过滤掉它们.我正在尝试使用来自Ajax的级联下拉列表.我知道脚本在一定程度上可以正常工作,因为默认的选定选项更改为进行选择".但是,其余的下拉列表不会填充.

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. 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.

这是两个下拉菜单.

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

我不知道错误是从哪里来的.感谢您的帮助.

I do not know where the error is coming from. Any help is appreciated.

推荐答案

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

A colleague helped me solve this problem. Firstly, the Ajax script was using the wrong URL. Secondly, my controller functions were unnecessarily complicated.

这是更新的AJAX脚本:

Here is the updated AJAX script:

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

这篇关于AJAX级联下拉列表ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆