如何解决foreach 循环 ASP.Net 核心 MVC 的问题
参考上面的前一篇文章。
foreach 循环或 Action ManageCategories 是否有问题?
页面正常加载,但是去掉category后,无法通过foreach循环
查看:
@model collector_forum.Models.Category.CategoryIndexModel
@{
ViewData["Title"] = "Categories";
}
<div class="container body-content">
<div class="row sectionHeader">
<div class="sectionheading">browse Categories</div>
<div class="sectionDescription">
<p>Welcome to <strong>Collectors Forum community</strong>. Posts are categorized by their theme</p>
<p>
Please read the Forum Guidelines before creating a new post.
@if (Context.User.Identity.IsAuthenticated)
{
<span>
You must be a
<a asp-area="Identity" asp-page="/Account/Register">registered member</a>
to create a new post
</span>
}
</p>
</div>
</div>
<div class="row" id="categoryIndexContent">
<table class="table table-hover" id="categoryIndexTable">
<tbody>
@foreach (var category in Model.CategoryList)
{
<tr>
<td>
@*<div class="forumlogo" style="background-image: url(@category.ImageUrl);"></div>*@
<div class="categoryData">
<div class="categoryTitle">
<a asp-controller="Forum" asp-action="Topic" asp-route-id="@category.Id">@category.Name</a>
</div>
<div class="categorySubTitle">
@if (category.HasRecentPost)
{
<div class="hasRecentPost">Hot</div>
}
</div>
</div>
</td>
<td>
<div class="categoryPostCount">
@category.NumberOfPosts Posts
</div>
<div class="categoryMemberCount">
@category.NumberOfUsers Users
</div>
</td>
<td>
<div class="categoryDescription">
@category.Description
</div>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
public IActionResult Delete(int id)
{
var category = _categoryService.GetById(id);
if (category == null)
{
ViewBag.ErrorMessage = $"Category with ID = {id} cannot be found";
return View("NotFound");
}
else
{
var result = _categoryService.Delete(id);
if (result.IsCompletedSuccessfully)
{
return RedirectToAction("ManageCategories");
}
return View("ManageCategories");
}
}
出了什么问题?
ManageCategories 操作:
public IActionResult ManageCategories()
{
var categories = _categoryService.GetAll()
.Select(category => new CategoryListingModel
{
Id = category.Id,Name = category.Title,Description = category.Description
});
var model = new CategoryIndexModel
{
CategoryList = categories
};
return View(model);
}
删除操作
public async Task Delete(int id)
{
var category = GetById(id);
_context.Remove(category);
await _context.SaveChangesAsync();
}
解决方法
你可以改变
return View("ManageCategories");
到
return RedirectToAction("ManageCategories");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。