Search code examples
.net-corerazor-pagespartials

how to stop razor partial persisting status message from one page to another


I have a razor solution with a partial that was included in the template solution in Visual Studio. The code in the partial is just a status message, like this:

@model string
@if (!String.IsNullOrEmpty(Model))
{
    var statusMessageClass = Model.StartsWith("Error") ? "danger" : "success";
    <div class="alert alert-@statusMessageClass alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        @Model
    </div>
}

In the page, it is referenced like this:

<partial name="_StatusMessage" model="Model.StatusMessage" />

In the pagemodel of the page it's been put in, the value of the message is set like this:

       [TempData]
        public string StatusMessage { get; set; }

        public IActionResult OnGet(int regFlow)
        {
            StatusMessage = "Blah blah status message";
            return Page();
        }

The problem is that although the status message displays fine on the page in question, it persists when I click onto another page that also has the StatusMessage partial declared in it - so it still displays a message that was relevant to the previous page, but is totally irrelevant to the current page. How can I stop it from persisting the message across pages?


Solution

  • You have annotated the StatusMessage with TempData, so it will be accessible for the next HTTP request as well. Why do you need to annotate it with TempData, if it needs to be displayed only in that page?