How to display Windows.Form.MessageBox in ASP.NET

2019-02-27 18:49发布

I want to display my validation error messages in the MessageBox. I have Four TextBoxes and One Button control. When I click the Button Control, the TextBoxes without the text to be shown in the MessageBox. I have almost done this, but the problem is When I click the Button, the MessageBox is opened as a minimized window. So it is difficult for the end user to realize. I want to display the MessageBox to the user when button clicks.

Here is my code, In the Button Click Event

ErrorMsg="";

if (TextBox1.Text == "")
{
    ErrorMsg += "Name is required!";
    ErrorMsg += "\n";
}
if (TextBox2.Text == "")
{
    ErrorMsg += "Address is required!";
    ErrorMsg += "\n";
}
if (TextBox3.Text == "")
{
    ErrorMsg += "Phone No. is required!";
    ErrorMsg += "\n";
}
if (TextBox4.Text == "")
{
    ErrorMsg += "City is required!";
    ErrorMsg += "\n";
}
if (ErrorMsg.Length == 0)
{
     //Some Code
}
else
{
    MessageBox.Show(ErrorMsg, "Existing Address", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Thanks in advance...

4条回答
Viruses.
2楼-- · 2019-02-27 19:30

You cannot use the Windows MessageBox in an ASP.NET application. It just doesn't make sense. An ASP.NET spits HTML/javascript/CSS so that's what you should be using to inform the user that something went wrong. So for example in an ASP.NET application you could use the RegisterStartupScript method to inject javascript into the page which will execute when the page is loaded and use the alert function:

ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('oops');", true);

Other more conventional techniques to perform validation in an ASP.NET application involve using the validation controls.

查看更多
男人必须洒脱
3楼-- · 2019-02-27 19:38

Why don't you just use the Ajax control toolkit?

You can then tweak the content of the pop up and I believe it's less intrusive than the windows style pop up message.

查看更多
戒情不戒烟
4楼-- · 2019-02-27 19:42

Create a function like

private void MessageBoxShow(Page page, string message)
{
    Literal ltr = new Literal();
    ltr.Text = @"<script type='text/javascript'> alert('" + message + "') </script>";
    page.Controls.Add(ltr);
}

and call it from any .aspx page like

MessageBoxShow(this,message);

the important thing is, if you use UserControl, then you need to change function parameter Page to UserControl.

查看更多
Root(大扎)
5楼-- · 2019-02-27 19:42

we can use windows Message Box Even in ASP.Net WEB Application Needs to Perform Steps Below

  1. Open Solution Explorer in Visual Studio and Right Click on Reference > Add Refrence
  2. Search system.windows and system .windows.form assemblies and add them
  3. then in your .aspx form where you want to use message box add assembly using system.windows and system.windows.form then you can use all functionalities like windows application in your web page
查看更多
登录 后发表回答