View:
<div class="form-group">
@Html.LabelFor(model => model.ProductID, "Vật tư", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ProductID", null , "Chọn sản phẩm", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ProductID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.BrandName, "Hãng", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.BrandName, new SelectList(" "), "Chọn Hãng", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.BrandName, "", new { @class = "text-danger" })
</div>
</div>
JQuery, Ajax
$(document).ready(function () {
$('#ProductID').change(function () {
$.get("/Admin/Sales/GetBrand", { ProductID: $("#ProductID").val() }, function (data) {
$("#BrandName").empty();
$.each(data, function (index, row) {
$("#BrandName").append("<option value='" + row.BrandName + "' >" + row.BrandName + "</option>")
});
});
});
});
Controller:
public JsonResult GetBrand(int ProductID)
{
db.Configuration.ProxyCreationEnabled = false;
List<BrandProduct> brands = db.BrandProducts.Where(x => x.ProductID == ProductID).ToList();
return Json(brands, JsonRequestBehavior.AllowGet);
}
Models:
a. Product:
public class Product
{
public int ProductID { get; set; }
[Display(Name ="Tên vật tư")]
public string ProductName { get; set; }
[Display(Name = "Chi tiết vật tư")]
public string ProductContent { get; set; }
[Display(Name = "Ảnh")]
public string Image { get; set; }
[Display(Name = "Ngày cập nhật")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> ModifiedDate { get; set; }
public virtual ICollection<Modem> Modems { get; set; }
public ICollection<Brand> Brands { get; set; }
public virtual ICollection<SupplierDetail> SupplierDetails { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
b. Brand
public class Brand
{
public int BrandID { get; set; }
[Display(Name ="Hãng")]
public string BrandName { get; set; }
public virtual ICollection<BrandProduct> BrandProducts { get; set; }
}

No comments:
Post a Comment