Reputation: 2489
In my ASP.NET C# application, there are many different error messages that I'd like to display.
The way I display my error message is by pop by via:
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('My error message here');", true);
return;
Since there are many different error messages (some repeated across pages) and I have so many different pages in my application - I'd like to put all the error message on a centralized page and reference to it somehow - so that when I need to change my error message, I only need to change in one page and not across ALL the pages.
What's the best way to do this?
I imagine I need to create a .cs page? And have a different ID for each of the error messages.
This seems like a very simple thing to do but I am a bit lost as to how to start on it.
Can someone advice the best way to do this?
Thanks.
Upvotes: 0
Views: 225
Reputation: 63065
I would add extension method to show the alerts and keep all the exception strings in resource file. then I can call the method as below
USAGE
this.ShowAlert(Resource1.MyException);
EXTENSION METHOD
using System;
using System.Web.UI;
namespace WebApplication1
{
public static class Extensions
{
public static void ShowAlert(this Control control, string message)
{
if (!control.Page.ClientScript.IsClientScriptBlockRegistered("msgbox"))
{
var script = String.Format("alert('{0}');", message);
control.Page.ClientScript.RegisterStartupScript(control.Page.GetType(), "msgbox", script, true);
}
}
}
}
Add resource file to your project and enter messages as string entries with meaning full names.
Upvotes: 6
Reputation: 1
JS method can be defined in
* the Master Page
* in the custom base class inherited by all the pages.
Upvotes: 0
Reputation: 39258
Since you appear to display JavaScript error messages I would create a JS include file and define the JS methods there. That way you can reuse the methods on all pages that include the JS file.
Upvotes: 1