简体   繁体   中英

Server Side Javascript Alert in C#

I'm attempting to create an alert that works on the server side, preferably using JavaScript. This alert is displayed if a user's input does not match a value pulled from a SQL server. The client side alert I was using was:

MessageBox.Show("User Input was not found. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

I attempted to replicate this by doing:

   string message = "User Input was not found. Please try again.";
   System.Text.StringBuilder sb = new System.Text.StringBuilder();
   sb.Append("<script type = 'text/javascript' runat = 'server'>");
   sb.Append("window.onload=function(){");
   sb.Append("alert('");
   sb.Append(message);
   sb.Append("')};");
   sb.Append("</script>");
   Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());

I also tried this:

   ClientScriptManager cs = Page.ClientScript;
   cs.RegisterClientScriptBlock(
   this.GetType(),
   " ",
   @"<script language=javascript>alert('User Input was not found. Please try again');</script>",
   true
   );

After this alert is displayed, I'd like to immediately redirect using Respone.Redirect("redirectpage.aspx") .

Is there a more effective solution to this issue? Am I missing something from my code? This is my first time using JavaScript for server side applications, so any detail would be appreciated.

Try using this method, it also has parameter to Redirect to Particular page

public class HTMLHelper
    {
        public static void jsAlertAndRedirect(System.Web.UI.Page instance, string Message, string Redirect_URL)
        {
            instance.Response.Write(@"<script language='javascript'>alert('" + Message + "');document.location.href='" + url + "'; </script>");
        }
    }

Call it using this,

HTMLHelper.jsAlertAndRedirect(this.Page, "Success Message !", ResolveUrl("~/default.aspx"));

Use ajax

$.ajax({
  url: validationUrl,
  data: {paramName: paramValue }
}).done(function(data ) {
  if (data.error)
    alert("error");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM