json级联下拉列表asp.net mvc

时间:2017-04-20 14:08:03

标签: jquery asp.net json asp.net-mvc asp.net-mvc-4

我目前正在关注该教程,以便在asp.net mvc中创建级联下拉列表。

https://chsakell.com/2013/09/25/master-detail-dropdown-lists-and-partial-views-with-jquery-ajax-in-mvc/

但是,第一个下拉框未加载制造商数据。我假设JSON有错误?我无法弄清楚代码有什么问题。

控制器:

 public ActionResult ManufacturerList()
        {
            var manufacturers = Models.Manufacturer.GetManufacturers();

            if (HttpContext.Request.IsAjaxRequest())
            {
                return Json(new SelectList(manufacturers.ToArray(), "ManCode", "ManName"), JsonRequestBehavior.AllowGet);
            }

        return RedirectToAction("Index");
    }

在模型中:

class Manufacturer
    {
        public string ManCode { get; set; }
        public string ManName { get; set; }

        public static IQueryable<Manufacturer> GetManufacturers()
        {
            return new List<Manufacturer>
{
new Manufacturer {
ManCode = "AC",
ManName = "ACER"
},
}.AsQueryable();
        }
    }

在视图中:

@using (Html.BeginForm("Index", "Home", FormMethod.Post,

                new

                {

                    id = "OrderLaptopFormID"

                }))

{

    <fieldset>

        <legend>Make an order</legend>

        <div>

            <label for="Manufacturers">Manufacturer</label>

        </div>

        <select id="ManufacturersID" name="Manufacturers"></select>

                </fieldset>

    <input type="submit" value="Return" id="SubmitID" />

}



<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>

<script src="@Url.Content("~/Scripts/GetManufacturer.js")"></script>

JS文件:

    $(document).ready(function () {
    var URL = 'home/ManufacturerList/';
    $.getJSON(URL, function (data) {
        var items = '<option value="">Select Manufacturer</option>';
        $.each(data, function (i, manufacturer) {
            items += "<option value='" + manufacturer.Value + "'>" + manufacturer.Text
            + "</option>";
        });
        $('#ManufacturersID').html(items);
    });
});

从这段代码中我会假设应填充制造商下拉列表,但事实并非如此。非常感谢任何人帮助MVC和JSON的新手。谢谢。 感谢你的时间。

更新:所以当我调试时,我收到以下错误: http://localhost:42523/Scripts/countryState.js中第1行第1行的未处理异常 0x800a1391 - JavaScript运行时错误:'$'未定义

1 个答案:

答案 0 :(得分:0)

很难说出问题出在哪里,但实际上,Manufacturer课程没有ValueText属性。相反,它有ManCodeManName

尝试:

    $.each(data, function (i, manufacturer) {
        items += "<option value='" + manufacturer.ManCode + "'>" + manufacturer.ManName
        + "</option>";
    });

此外,无需返回IQueryable,只需返回IEnumerable即可。所以不需要.AsQueryable()

   public static IEnumerable<Manufacturer> GetManufacturers()
   {
       return new List<Manufacturer> {
            new Manufacturer {
                ManCode = "AC",
                ManName = "ACER"
           }
       };
   }

最后,不要从方法返回SelectList,只需返回列表

        if (HttpContext.Request.IsAjaxRequest())
        {
            return Json(manufacturers, JsonRequestBehavior.AllowGet);
        }