这是我的控制器:
public async Task<IActionResult> CreatePortfolioCategory(CreatePortfolioCategoryViewModel createPortfolioCategoryViewModel)
{
if (!ModelState.IsValid)
{
return View(createPortfolioCategoryViewModel);
}
var result = await _siteService.CreatePortfolioCategory(createPortfolioCategoryViewModel);
switch (result)
{
case CreatePortfolioCategoryResult.NotFound:
ViewBag.ErrorText = "Error";
return View(createPortfolioCategoryViewModel);
case CreatePortfolioCategoryResult.Created:
ViewBag.SuccessText = "Successful Create";
break;
}
return RedirectToAction("Index");
}
它在数据库中创建成功并重定向到索引,但在索引上不显示此错误和成功消息
我在view上写了这段代码,但是viewbage上的这条消息没有显示在view上。它只显示“成功”
<div>
@if (!string.IsNullOrEmpty(ViewBag.ErrorText))
{
<div class="alert alert-danger">
<p>@ViewBag.ErrorText</p>
</div>
}
@if (!string.IsNullOrEmpty(ViewBag.SuccessText))
{
<div class="alert alert-success">
<p>@ViewBag.SuccessText</p>
</div>
}
<h2> Successfull </h2>
这是service上的create方法:
public async Task<CreatePortfolioCategoryResult> CreatePortfolioCategory(CreatePortfolioCategoryViewModel createPortfolioCategoryViewModel)
{
if (createPortfolioCategoryViewModel.ParentId != null && !await _portfolioRepository.IsExistPortfolioCategory(createPortfolioCategoryViewModel.ParentId.Value))
return CreatePortfolioCategoryResult.NotFound;
PortfolioCategory portfolioCategory = new PortfolioCategory()
{
PortfolioTitle = createPortfolioCategoryViewModel.PortfolioTitle,
NameInUrl = createPortfolioCategoryViewModel.NameInUrl,
IsDelete = createPortfolioCategoryViewModel.IsDelete,
IsActive = createPortfolioCategoryViewModel.IsActive,
Order = createPortfolioCategoryViewModel.Order,
ParentId = createPortfolioCategoryViewModel.ParentId
};
await _portfolioRepository.CreatePortfolioCategory(portfolioCategory);
await _portfolioRepository.SaveChange();
return CreatePortfolioCategoryResult.Created;
}
1条答案
按热度按时间bis0qfac1#
您没有将
ViewBag.SuccessText
的值传递给Index
方法,因此在Index
的视图中,ViewBag.SuccessText
始终是空值。当
SiteService
返回CreatePortfolioCategoryResult.NotFound
时,返回的视图是CreatePortfolioCategory.cshtml
,当SiteService
返回CreatePortfolioCategoryResult.Created
时,返回的视图是Index.cshtml
。所以只能在Index.cshtml
中判断SuccessText
是否为空,然后在CreatePortfolioCategory.cshtml
中判断ErrorText
是否为空。你可以参考我下面的测试代码:
控制器:
Index.cshtml:
CreatePortfolioCategory.cshtml:
测试结果:
返回
CreatePortfolioCategoryResult.NotFound
时:返回
CreatePortfolioCategoryResult.Created
时: