[英]MVC cascading dropdown
我有两个表Manufacturer表和ManufacturerModel表。 我正在尝试填充两个下拉列表。 制造商列表,然后根据选择的制造商,将显示一个型号列表。 但是我实现的方法不起作用。 它什么也没做。
我创建了一个包含两个模型的新ViewModel
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>');
});
}
});
});
});
ManufacturerModelDD
是一个不继承自DbContext
。 因此,我不确定该类的对象可用于访问实体。
您可以考虑创建数据库上下文类的对象并访问您的实体数据。
假设您的数据库上下文类如下所示
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>');
});
}
另外,请确保您在“脚本”部分下具有查看特定的javascript代码
@section Scripts
{
<script>
$(function(){
//your code goes here.
});
</script>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.