In this article I will explain with an example, how to display
MessageBox using
JavaScript in ASP.Net Core (.Net Core) Razor Pages.
Model
The Model class consists of following properties.
public class PersonModel
{
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
Razor PageModel (Code-Behind)
Inside the PersonModel, first the public property of PersonModel class is created.
The PageModel consists of following Handler methods.
Handler method for handling Home GET operation
This Handler method is left empty as it is not required.
Handler method for handling POST operation
Inside this Handler method, a String Message is set in the
ViewData object.
public class IndexModel : PageModel
{
public void OnGet()
{
}
public void OnPostSubmit()
{
ViewData["Message"] = "Your details have been saved successfully.";
}
}
Razor Page (HTML)
HTML Markup
Inside the Razor Page, the ASP.Net TagHelpers is inherited.
The Razor Page consists of three TextBoxes 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.
Submitting the Form
When the
Submit Button is clicked then, the
ViewData object is checked for NULL and if it is not NULL then, the value of the
ViewData object is displayed using
JavaScript Alert
MessageBox.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model MessageBox_JavaScript_Core_Razor.Pages.IndexModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Name: </td>
<td><input type="text" asp-for="Person.Name" /></td>
</tr>
<tr>
<td>City: </td>
<td><input type="text" asp-for="Person.City" /></td>
</tr>
<tr>
<td>Country: </td>
<td><input type="text" asp-for="Person.Country" />td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save" asp-page-handler="Submit" />td>
</tr>
</table>
</form>
@if (ViewData["Message"] != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewData["Message"]");
};
</script>
}
</body>
</html>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads