【发布时间】:2019-10-20 07:23:00
【问题描述】:
我开始学习实体框架和 asp.net,我想使用所有的 CRUD 操作。 我有任务和类别模型,它们是多对多的关系。在我的数据库中有 3 个表:1.Task(它包含 Id、Title、Description..)、2.Category(它包含 categoryId 和 categoryName)和 3. TaskCategory(包含 Id (taskId) 和 categoryId)。
除了使用下拉菜单向任务添加多个类别外,我设法完成了所有我想做的事情。我创建了下拉列表并加载了类别,并且我知道如何将一个类别添加到任务中(当关系为 1:N 时)(asp-for="CategoryId")。对于多项选择,我尝试使用 selectedCategories (list od integers - ids) 而不是 CategoryId 但我不知道如何处理该列表。将任务保存在控制器中时如何在TaskCategory中加入类别和任务(换句话说:如何将类别保存到任务中)?
AddTask.cshtml
<div class="form-group">
<label class="control-label">Category</label>
<select class="select-picker" asp-for="selectedCategories"
asp-items="@(new SelectList(Model.Categories, "CategoryId", "CategoryName"))" multiple>
</select>
</div>
<script>
...
$('.select-picker').selectpicker('toggle');
</script>
HomeController.cs
public IActionResult AddTask()
{
var categories = _categoryRepository.GetAllCategories().OrderBy(c => c.CategoryName);
var taskCategories = _taskCategoryRepository.GetAllTaskCategories().OrderBy(tc => tc.Id);
var homeViewModel = new HomeViewModel()
{
Task = null,
TaskCategory = null,
Categories = categories.ToList(),
TaskCategories = taskCategories.ToList(),
selectedCategories = new List<int>()
};
return View(homeViewModel);
}
[HttpPost]
public IActionResult AddTask(Task task, List<int> selected)
{
// foreach (var selectedCategoryId in selected)
// {
//
// }
_taskRepository.AddTask(task);
return RedirectToAction("Index");
return View();
}
这样我可以在数据库中获取任务,但当然没有保存任何类别。
【问题讨论】:
标签: c# asp.net entity-framework asp.net-core razor-pages