Change page title on error ASP.NET Core MVC without javascript

525 Views Asked by At

I am working on an ASP.NET Core 3.1 MVC application.

I need to append a page title with error: whenever the server validation fires through clicking on a button and Model state has errors.

At the moment - I am changing page title on each page through using shared view as follows:

Here is the logic defined for page title - in the _Layout.cshtml.

@if (ViewData["Title"] != null)
{
<title> 
    @ViewData["Title"] - Sample Application
</title>
}

And on each viewpage.cshtml - we are changing page title the following way. Please note, if I define the logic of changing page title with

ViewData["Title"] = "Error :" +ViewData["Title"]

it works fine.

@page
@model SampleModel

@{
    ViewData["Title"] = "What do you do?";
}

@if (!ViewData.ModelState.IsValid)
{
    ViewData["Title"] = "Error: " + ViewData["Title"];
}

<partial name="_ErrorSummary" model="ModelState" />

Also, I have a shared components for displaying error summary which is on each page.

<partial name="_ErrorSummary" model="ModelState" />

And this is the code inside the partial view

@model Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary

@if (!Model.IsValid)
{    
   ViewData["Title"] = "Error: " + ViewData["Title"];  //  I want something like this
     
   <div class="govuk-error-summary" aria-labelledby="error-summary-title" role="alert" data-module="error-summary">
   <h2 class="govuk-error-summary__title" id="error-summary-title">
        There is a problem
   </h2>
   <div class="govuk-error-summary__body">
        <ul class="govuk-list govuk-error-summary__list">
            @foreach (var modelError in Model)
            {
                var errorField = modelError.Key;
                foreach (var error in modelError.Value.Errors)
                {
                    <li>
                        <a href="#@errorField">@error.ErrorMessage</a>
                    </li>
                }
            }
        </ul>
    </div>
</div>
}

So validation is happening on all server sides (We are not using any javascript).

What I want whenever a button is clicked and it throws error on that page summary, the Page title should get appended with "Error : " + existing Page title

How do I do this from one centralised position. Please if anyone can help. Ideally I like to do this in shared error summary view or any bright ideas. Many thanks

0

There are 0 best solutions below