var successful = await _articleCategoryService.AddArticleCategoryAysnc(articleCategory);
if (successful)
return RedirectToAction("Index");
else
return BadRequest("失败");
}
return View(articleCategory);
}<br>
[HttpGet]
public async Task<IActionResult> Edit(int id)
{
if (string.IsNullOrEmpty(id.ToString()))
return NotFound();
var articleCategory = await _articleCategoryService.FindArticleCategoryAsync(id);
if (articleCategory == null)
return NotFound();
return View(articleCategory);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, ArticleCategory articleCategory)
{
if (id != articleCategory.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
var result = await _articleCategoryService.UpdateArticleCategoryAsync(id, articleCategory);
}
catch (Exception ex)
{
return BadRequest("编辑失败");
}
return RedirectToAction("Index");
}
return View(articleCategory);
}
[HttpGet]
public async Task<IActionResult> Delete(int id)
{
var result = await _articleCategoryService.DeleteArticleCategoryAsync(id);
if (result)
return RedirectToAction("Index");
else
return BadRequest("删除失败");
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteAll(string[] ids)
{
int countSuccessDel = 0;//记录删除成功的数据条数
int countFailedDel = 0;//记录删除成功的数据条数
foreach (string id in ids)
{
if (await _articleCategoryService.DeleteArticleCategoryAsync(int.Parse(id)))
countSuccessDel++;
else
countFailedDel++;
}
if (countSuccessDel > 0)
return RedirectToAction("Index");
else
return BadRequest("删除失败");
}
public async Task<IActionResult> Details(int id)
{
if (string.IsNullOrEmpty(id.ToString()))
return NotFound();
var articleCategory = await _articleCategoryService.FindArticleCategoryAsync(id);
if (articleCategory == null)
return NotFound();
return View(articleCategory);
}
[HttpGet]
public async Task<IActionResult> GetCategory()
{
var items = await _articleCategoryService.GetArticleCategory();
return View(items);
}
public IActionResult GetParentName(int id)
{
var category = _appDbContext.ArticleCategory.Where(x => x.Id == id).FirstOrDefault();
if (category != null)
return Content(category.Title);
else
return Content("");
}
}
复制代码
注意,在Index的Action中的我用了个简单的Linq关联查询
因为,父Id与Id都是存在一张表中,关联子查询在使用时要用到:from m in T1.DefaultIfEmpty() 这一句,可以将空也计算在内,否则,会排除掉最前面2行(下图),我的本意sql语句是:
Select a.Id,a.Title,a.parentId,b.Title as ParentName,a.sort from ArticleCategory a
Left join ArticleCategory b on a.ParentId = b.Id ,这样可以将父Id的名称作为一个新列放在查询表中。