This is my controller:
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");
}
it create successful in database and redirect to index but it does not show this error and successful message on index
I write this code on view but this message on viewbage doesn't show on view. it show just " Successful"
<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>
This is the create method on service:
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;
}
You did not pass the value of
ViewBag.SuccessTextto theIndexmethod, soViewBag.SuccessTextis always a null value in the view ofIndex.When
SiteServicereturnsCreatePortfolioCategoryResult.NotFound, the view you return isCreatePortfolioCategory.cshtml, and whenSiteServicereturnsCreatePortfolioCategoryResult.Created, the view you return isIndex.cshtml. So you can only judge whether theSuccessTextis empty inIndex.cshtml, and then judge whetherErrorTextis empty inCreatePortfolioCategory.cshtml.You can refer to my test code below:
Controller:
Index.cshtml:
CreatePortfolioCategory.cshtml:
Test Result:
When
CreatePortfolioCategoryResult.NotFoundis returned:When
CreatePortfolioCategoryResult.Createdis returned: