我试图提供一个视图,人们可以在其中创建类别和子类别列表。因此,我需要允许用户动态添加行。 每行将允许用户添加类别,然后如果他们希望子类别。对于第一行,我可以使用 asp-items 属性绑定到 ViewBag 中的 SelectList ,但是当我添加新行时通过JS我不能这样做,我已经尝试了两种方法JS(都在代码中显示):
有谁知道我如何填充新添加的行?另外,我如何将数据中的enetred绑定到我的模型中;是否必须在控制器中完成?
代码如下:
<script type="text/javascript">
$(document).ready(function () {
var categories = "@ViewBag.Categories";
var catOptions = '';
for (var i = 0; i < categories; i++) {
catOptions = catOptions + '<option value="' + categories[i].CategoryId + '">' + categories[i].Name + '</option>'
}
$(document).on("click", "#btnAddCat", function () {
var newCat =''+
'<tr class="categorieRows">' +
'<td colspan="2">' +
'<select>' +
catOptions +
'</select>' +
'</td>' +
'<td>' +
'<button type="button" id="btnAddSubCat" class="btn btn-xs btn-primary classAdd">Add Sub Category</button>' +
'</td>' +
'</tr>';
$('#categoryTable').append(newCat);
});
$(document).on("click", "#btnAddSubCat", function () {
var newSubCat = '' +
'<tr class="categorieRows">' +
'<td></td>' +
'<td>' +
'<select asp-items="ViewBag.SubCategories"></select>' +
'</td>' +
'<td></td>' +
'</tr>';
$('#categoryTable').append(newSubCat);
});
});
</script>
&#13;
@model IEnumerable<Categories>
@{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<h4>Surveys</h4>
<hr />
<table class="table table-striped" id="categoryTable">
<thead>
<tr>
<th>
Category
</th>
<th>
Sub Categories
</th>
<th>
<button type="button" id="btnAddCat" class="btn btn-xs btn-primary classAdd">Add Category</button>
</th>
</tr>
</thead>
<tbody>
<tr class="categorieRows">
<td colspan="2">
<select asp-items="ViewBag.Categories"></select>
</td>
<td>
<button type="button" id="btnAddSubCat" class="btn btn-xs btn-primary classAdd">Add Sub Category</button>
</td>
</tr>
</tbody>
</table>
<div>
<a asp-action="Index">Back to List</a>
</div>
&#13;
答案 0 :(得分:0)
使用Ajax调用来检索类别数据:
<script>
$(document).ready(function () {
$(document).on("change", "#selectCategroy", function () {
var subCat = this;
$.ajax({
url: "ReturnJsonSubCategories/?categoryId=" + $(subCat).val(),
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: JSON,
success: function (result) {
var categories = "";
$(result).each(function () {
categories = categories + '<option value="' + this.subCategoryId + '">' + this.name + '</option>'
});
var subCateList = $("#selectSubCategroy");
subCateList.empty();
subCateList.append(categories);
},
error: function (data) {
return "Error";
}
});
});
});
</script>
&#13;
服务器端代码如下:
public JsonResult ReturnJsonSubCategories(int categoryId)
{
var jsonData = _context.SubCategories.Where(x => x.CategoryId == categoryId).ToList();
return Json(jsonData);
}