In this article I will explain with an example, how to display message using JavaScript Alert MessageBox in ASP.Net Core Razor Pages.
The message sent from Razor PageModel (Code-Behind) to Razor PageModel (HTML) will be displayed in JavaScript Alert MessageBox using ViewData object.
Note: For beginners in ASP.Net Core Razor Pages, please refer my article ASP.Net Core Razor Pages: Hello World Tutorial with Sample Program example.
 
 
Razor PageModel (Code-Behind)
The PageModel consists of two Action Handler methods.
Handler method for handling GET operation
This Handler method is left empty as it is not required.
 
Handler method for handling Button Click and POST operation
This Handler method handles the POST call when the Submit Button is clicked and the Form is submitted.
Note: The name of the parameter must be same as the value of name attribute specified for the Form element.
 
The name value fetched from the Form collection and the Current Server Date and Time is set to a ViewData object.
public class IndexModel : PageModel
{
    public void OnGet()
    {
    }
 
    public void OnPostSubmit(string name)
    {
        ViewData["Message"] = string.Format("Hello {0}.\\nCurrent Date and Time: {1}", name, DateTime.Now.ToString());
    }
}
 
 
Razor Page (HTML)
The HTML of Razor Page consists of an HTML Form with a TextBox and a Submit Button.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostSubmit but here it will be specified as Submit when calling from the Razor HTML Page.
 
When the Submit Button is clicked, the Form gets submitted and the value of the TextBox are sent to the PageModel.
Finally, the ViewData object named Message is checked for NULL and if it is not NULL then the value of the object is displayed using JavaScript Alert MessageBox.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Razor_JavaScript_Alert.Pages.IndexModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <form method="post">
        <input type="text" id="txtName" name="name"/>
        <input type="submit" id="btnSubmit" value="Get Current Time" asp-page-handler="Submit"/>
    </form>
    @if (ViewData["Message"] != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewData["Message"]");
            };
        </script>
    }
</body>
</html>
 
 
Screenshot
ASP.Net Core Razor Pages: Display JavaScript Alert Message Box
 
 
Downloads