【发布时间】:2018-07-14 13:25:28
【问题描述】:
我不明白为什么它是未定义的。 在控制器中,Create Action 设置为类别下拉列表。
public IActionResult Create()
{
var model = new TechnicialSpecsViewModel();
List<Product> categories = _productService.GetAllParents();
model.CategoryList = (from i in categories
select new SelectListItem
{
Value = i.Id.ToString(),
Text = i.Name
}).ToList();
model.CategoryList.Insert(0, new SelectListItem { Value = "", Text = "Select", Selected = true });
return View(model);
}
如果我从类别下拉列表中选择一个选项,请将类别 ID 发送到 ProductList 操作。所以我可以得到 categoryId == id 的产品列表
[HttpPost]
public JsonResult ProductList(int id)
{
List<Product> products = _productService.GetByParent(id);
return Json(new SelectList(products, "Id", "Name"));
}
它很完美,但是当我查看产品下拉菜单时,它似乎都未定义。
这是我的功能,
<script type="text/javascript">
$(document).ready(function () {
$("#CategoryId").change(function () {
var id = $(this).val();
var productId = $("#ProductId");
productId.empty();
$.ajax({
url: '/TechnicialSpecs/ProductList',
type: 'POST',
dataType: 'json',
data: { 'id': id },
success: function (data) {
$.each(data, function (index, option) {
productId.append('<option value=' + option.Value + '> ' + option.Text + ' </option>');
});
}
});
});
});
</script>
并查看,
<div class="form-group">
@Html.DropDownListFor(x => x.CategoryId, Model.CategoryList, new { @class = "bs-select form-control" })
</div>
</div>
<div class="form-group">
<select id="ProductId" name="ProductId" asp-for="Product" asp-items="@(new SelectList(string.Empty, "Id", "Name"))"></select>
</div>
</div>
另外,两个模型都是同一类型的,我真的不明白为什么这些未定义。
【问题讨论】: