Search code examples
asp.netasp.net-coreviewcontrollerviewbag

does not show error message on view data in ASP.NET


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;

    }

Solution

  • You did not pass the value of ViewBag.SuccessText to the Index method, so ViewBag.SuccessText is always a null value in the view of Index.

    When SiteService returns CreatePortfolioCategoryResult.NotFound, the view you return is CreatePortfolioCategory.cshtml, and when SiteService returns CreatePortfolioCategoryResult.Created, the view you return is Index.cshtml. So you can only judge whether the SuccessText is empty in Index.cshtml, and then judge whether ErrorText is empty in CreatePortfolioCategory.cshtml.

    You can refer to my test code below:

    Controller:

    public IActionResult Index(string? successText)
    { 
        ViewBag.SuccessText = successText;
        return View();
    }
    
    [HttpGet]
    public IActionResult CreatePortfolioCategory()
    { 
        return View();
    }
    
    [HttpPost]
    public async Task<IActionResult> CreatePortfolioCategory(CreatePortfolioCategoryViewModel createPortfolioCategoryViewModel)
    {
        if (!ModelState.IsValid)
        {
            return View(createPortfolioCategoryViewModel);
        }
    
        var result = _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", new { successText = ViewBag.SuccessText });
    }
    

    Index.cshtml:

    <div>
        @if (!string.IsNullOrEmpty(ViewBag.SuccessText))
        {
            <div class="alert alert-success">
                <p>@ViewBag.SuccessText</p>
            </div>
        }
    </div>
    

    CreatePortfolioCategory.cshtml:

    @if (!string.IsNullOrEmpty(ViewBag.ErrorText))
    {
        <div class="alert alert-danger">
            <p>@ViewBag.ErrorText</p>
        </div>
    }
    <form method="post" asp-action="CreatePortfolioCategory" >
        <div>ParentId</div>
        <div><input type="number" asp-for="@Model.ParentId" /></div>
        <div>PortfolioTitle</div>
        <div><input type="text" asp-for="@Model.PortfolioTitle" /></div>
        <div>NameInUrl</div>
        <div><input type="text" asp-for="@Model.NameInUrl" /></div>
        <div>IsDelete</div>
        <div><input type="checkbox" asp-for="@Model.IsDelete" /></div>
        <div>IsActive</div>
        <div><input type="checkbox" asp-for="@Model.IsActive" /></div>
        <div>Order</div>
        <div><input type="text" asp-for="@Model.Order" /></div>
        <div><input type="submit" value="Submit" /></div>
    </form>
    

    Test Result:

    When CreatePortfolioCategoryResult.NotFound is returned: enter image description here

    When CreatePortfolioCategoryResult.Created is returned: enter image description here