質問

I have this code to display a javascript message alert box from my server,it works fine but now i want to move the entire code into one static class so that i can call it from anywhere in my application without having to copy the code again to that page, this is the function i use right now:

private static void MessageBox(string msg)
{
    Label lbl = new Label();
    lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
    Page.Controls.Add(lbl);
}

Now i want to be able to call this function from a static class on any webform i create in my application.

This is the error i get underlined on "Page.Control.Add(lbl)": enter image description here

役に立ちましたか?

解決

In the code-behind Page is a property of type Page (confusing I know!) so it refers to an instance of the Page class. To your static method outside of this scope it only know of the class Page and so the compiler sees you attempting to call a static property called Controls which doesn't exist on the Page class and so throws an error your way.

You will need to pass the Page instance to the MessageBox method:

public static void MessageBox(Page page, string msg)
{
    Label lbl = new Label();
    lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
    page.Controls.Add(lbl);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top