2016-07-15 68 views
0

我有两个表一个制造商表和ManufacturerModel表。我正在尝试填充两个下拉列表。制造商名单,然后根据选择哪个制造商,它会列出模型列表。但是我实现的不起作用。它什么都不做。MVC级联式下拉

我创建结合了两种模式

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

一个新视图模型,我已经在我希望他们在控制器中创建2种功能。

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

+0

哪一部分是不工作的看法特定的JavaScript代码? – Shyju

+0

我不确定。我的下拉菜单是空白的。我不确定它是我的函数还是ajax。 –

回答

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部分

@section Scripts 
{ 
    <script> 
    $(function(){ 
     //your code goes here. 
    }); 
    </script> 
} 
+0

我确信我的代码看起来和上面完全一样,而且什么也没有。它可以与我的下拉列表 - @ Html.DropDownList(“dropdownManufacturer”,新的SelectList(string.Empty,“价值”,“文本”),“请选择一个制造商”,新{@style =“width:250;” }) –

+0

刚刚尝试相同的代码,它的工作。你确定'db.Manufacturers'返回一些东西吗?打开浏览器控制台并查找js错误 – Shyju

+0

这与您使用的jQuery版本和/或您将它们放入什么顺序有关吗? –