Search code examples
c#asp.net-corerazorrazor-pages

How to print a message to user in Razor Pages


I am creating a web app with Razor Pages and I'm running into an issue. I am trying to send a message to the user when an exception is thrown. I'm imagining something similar to MessageBox class from System.Windows.Forms. Any ideas on whether this is possible or how to do it? Any help is appreciated.

try
{
    double oneone = Convert.ToDouble(Project.projectServicesCost);
}
catch (Exception e)
{
    //Throw message to user saying projectServicesCost is not in the correct 
    //format and therefore couldn't convert to double
}

Here's an example from my code.


Solution

  • You can use some library like NToastNotify.

    You can follow the below steps to implement it:

    1.Install NToastNotify package using Package Console Manager:

    Install-Package NToastNotify
    

    2.Configure NToastNotify service and

    services.AddRazorPages().AddNToastNotifyNoty();
    

    3.Add the middlware:

    app.UseNToastNotify();
    

    4.Add the view in _Layout page:

    @await Component.InvokeAsync("NToastNotify")
    

    5.Dependency injection IToastNotification then you can use it

    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly IToastNotification _toastNotification;
    
        public IndexModel(ILogger<IndexModel> logger, IToastNotification toastNotification)
        {
            _logger = logger;
            _toastNotification = toastNotification;
        }
    
        public void OnGet()
        {
            try
            {
                throw new NullReferenceException();
            }
            catch
            {
                _toastNotification.AddErrorToastMessage("Some Error Message");
            }
        }
    }
    

    Result:

    enter image description here

    For more details, refer to: https://github.com/nabinked/NToastNotify