MVC级联下拉列表

时间:2016-07-15 19:49:45

标签: ajax asp.net-mvc

我有两个表,一个制造商表和ManufacturerModel表。我想填充两个下拉列表。制造商列表,然后根据选择的制造商,它将显示模型列表。但我实施的内容并不奏效。它没有做任何事情。

我创建了一个包含两个模型的新ViewModel

public class ManufacturerModelDD
{
    public DbSet<Manufacturer> Manufacturers { get; set; }
    public DbSet<ManufacturerModel> ManufacturerModels { get; set; }
}

我在控制器中创建了两个我希望它们的功能。

ManufacturerModelDD mm = new ManufacturerModelDD();

    public JsonResult GetManufacturers()
    {
        return Json(mm.Manufacturers.ToList(), JsonRequestBehavior.AllowGet);
    }

    public JsonResult GetModelsByManufacturerID(string manufacuterId)
    {
        int Id = Convert.ToInt32(manufacuterId);

        var models = from a in mm.ManufacturerModels where a.ManufacturerID == Id select a;

        return Json(models);
    }

在我看来,我有

<script>
$(function(){
$.ajax({
    type: "GET",
    url: "/Device/GetManufacturers",
    datatype: "Json",
    success: function (data) {
        $.each(data, function (index, value) {
            $('#dropdownManufacturer').append('<option value="' + value.ManufacturerID + '">' +
            value.Manufacturer1 +'</option>');
        });
    }
});

    $('#dropdownManufacturer').change(function(){
        $('#dropdownModel').empty();

        $.ajax({
            type: "POST",
            url: "/Device/GetModelsByManufacturerID",
            datatype: "Json",
            data: { manufacturerID: $('#dropdownManufacturer').val() },
            success: function (data) {
                $.each(data, function (index, value) {
                    $('#dropdownModel').append('<option value="' + value.ManufacturerID + '">' +
                        value.Model + '</option>');
                });
            }
        });
    });
    });   

1 个答案:

答案 0 :(得分:0)

ManufacturerModelDD是一个不从DbContext继承的类。所以我不确定 该类的对象可用于访问实体。

您可以考虑创建数据库上下文类的对象并访问您的实体数据 假设您的db上下文类看起来像这样

public class YourDbContext : DbContext
{
    public DbSet<Manufacturer> Manufacturers { get; set; }
    public DbSet<ManufacturerModel> ManufacturerModels { get; set; }
}

您可以使用此类的对象。

public JsonResult GetManufacturers()
{
    var db = new YourDbContext();
    var data = db.Manufacturers
               .Select(s=> new {Id =s.ManufacturerID ,
                                                 Name = s.ManufacturerName}).ToList();
    return Json(data , JsonRequestBehavior.AllowGet);
}

确保在循环数据时使用正确的属性。

success: function (data) {
    $.each(data, function (index, value) {
        $('#dropdownManufacturer').append('<option value="' + value.Id+ '">' +
        value.Name+'</option>');
    });
}

另外,请确保在scrips部分

下有特定于视图的javascript代码
@section Scripts
{
  <script>
     $(function(){
         //your code goes here.
     });
  </script>
}
相关问题