I tried searching the internet for ways to display a javascript alert box in asp.net, but none of them worked.
My code:
string message;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
if ((int) Application["taken"] == 1)
{
message = "Username and email already in use!";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Username and email already in use!')", true);
}
else if ((int) Application["taken"] == 2)
{
message = "Username already in use!";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Username already in use!')", true);
}
else if ((int) Application["taken"] == 3)
{
message = "Email already in use!";
sb.Append("<script type = 'text/javascript'> window.onload=function(){alert('" + message + "')} </script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
what do I need to do?
You cannot call script twice, instead write code for alert twice in same script.
You can write your javascript method at your aspx page or can write in a javascript file and include it. Then register it at cs page as
ScriptManager.RegisterStartupScript(this, this.GetType(), “ShowStatus”, “javascript:ShowMessages(‘First Message’,’Second Message’);”, true);
function ShowMessages(msg1, msg2) {
alert(msg1);
alert(msg2);
}
For details please click on this link
Could you try RegisterStartupScript ?
ClientScript.RegisterStartupScript(this.GetType(), "alertMessage", "alert('Username already in use!')", true);
Related
I have a query which returns a DataSet. After that I check whether records are available or not. If no records available I want to display error message, exit from the process and redirect to another page. Methods available in below the exiting method should not execute.
Here is the code I have so far.
ds = dba.loadEmpInfo(number, searchType, department);
string appNumber = "";
if (ds.Tables[0].Rows.Count > 0)
{
appNumber = ds.Tables[0].Rows[0]["Ref_no"].ToString();
workDS = dba.workExp(appNumber, searchType);
}
else
{
WebMsgBox.Show("No Record relevant to this app number are available");
}
If you want to show Alert message from code behind use below syntax,
ScriptManager.RegisterStartupScript(Control control, Type type,string key, string script,bool addScriptTags);
i.e, in the else part
{
ScriptManager.RegisterStartupScript(this, GetType(), "Alert",
"alert('No Record relevant to this app number are available!');", true);
// Now Re-direct to the next page as you wish
Response.Redirect("yourPage.aspx");
}
I have a helper created as follows:-
public static MvcHtmlString FileDomElement(this HtmlHelper helper, FileUpload fileUpload)
{
string strOutput = string.Empty;
if (fileUpload.MultipleFile)
{
if (string.IsNullOrEmpty(fileUpload.MimeType))
{
strOutput = "<input type=\"file\" multiple=\"multiple\" id=\"chooseFiles\" value=\"Choose File(s)\" onchange=\"ehDisplayFileNames();\" style=\"opacity: 0\" >";
}
else
{
strOutput = "<input type=\"file\" multiple=\"multiple\" id=\"chooseFiles\" value=\"Choose File(s)\" accept=\"" + fileUpload.MimeType + "\" onchange=\"ehDisplayFileNames();\" style=\"opacity: 0;\">";
}
}
else
{
if (string.IsNullOrEmpty(fileUpload.MimeType))
{
strOutput = "<input type=\"file\" id=\"chooseFiles\" value=\"Choose File(s)\" onchange=\"ehDisplayFileNames();\" style=\"opacity: 0;\">";
}
else
{
strOutput = "<input type=\"file\" id=\"chooseFiles\" value=\"Choose File(s)\" accept=\"" + fileUpload.MimeType + "\" onchange=\"ehDisplayFileNames();\" style=\"opacity: 0;\">";
}
}
return MvcHtmlString.Create(strOutput);
}
Now in the onchange event of the file I want to send the button to the backend. Because I have multiple file input elements on a single page. So I want to detect which one was clicked.
Please help me with this.
Thanks
Abhishek
You could try catching the event info and using that to get a reference to the sender:
function ehDisplayFileNames(event) {
console.log(event.target.id + ' has fired the event!');
}
Your markup would need to send the event:
onchange="ehDisplayFileNames(event);"
Mark's comment above is very true, once you have a client side id you will still need some type of Ajax call to get this info back to the server.
I am having a web page and i applied script manager on it. On the page load i am checking some condition and showing a Javascript ShowModalDialog from code and it is working fine.
int isAnyNonProdTaskActive = _nonProduction.IsAnyTaskActive(UserIDFromDB);
if (isAnyNonProdTaskActive > 0)
{
//Displays and Logs Message
_loggerDetails.LogMessage = "EmployeeQuotient.Production.Page_Load() One NonProduction incomplete task found, NonProductionTimeEntryID : " + isAnyNonProdTaskActive.ToString();
_writeLog.LogDetails(_loggerDetails.LogLevel_Info, _loggerDetails.LogMessage);
Session["TaskActiveNonProd"] = isAnyNonProdTaskActive;
Page page = HttpContext.Current.CurrentHandler as Page;
//Displays and Logs Message
_loggerDetails.LogMessage = "EmployeeQuotient.Production.Page_Load() Opening ElapsedClockNonProd.aspx to complete the incomplete task id :" + isAnyNonProdTaskActive.ToString();
_writeLog.LogDetails(_loggerDetails.LogLevel_Info, _loggerDetails.LogMessage);
ScriptManager.RegisterStartupScript(page, page.GetType(), "OpenModalDialog", "<script type=text/javascript>window.showModalDialog('ElapsedClockNonProd.aspx?code=" + isAnyNonProdTaskActive.ToString() + "', null, 'unadorned:yes ;resizable:0 ;dialogWidth:300px ;dialogHeight:300px ;status:no ;scroll:no ;status=no;'); </script>", false);
}
The same code i am applying on a Button on the same page then i am getting error.The error message is :- Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: The script tag registered for type 'ASP.associates_production_aspx' and key 'OpenModalDialog' has invalid characters outside of the script tags: window.showModalDialog('ElapsedClockNonProd.aspx?code=464', null, 'unadorned:yes ;resizable:0 ;dialogWidth:300px ;dialogHeight:300px ;status:no ;scroll:no ;status=no;'); . Only properly formatted script tags can be registered.
Guide me that how i fix this error.I am not getting that why on the button click it is not working but while page load the same script is working without any issues..
ScriptManager.RegisterStartupScript(page, page.GetType(), "OpenModalDialog", "<script type='text/javascript'>window.showModalDialog('ElapsedClockNonProd.aspx?code=" + isAnyNonProdTaskActive.ToString() + "', null, 'unadorned:yes ;resizable:0 ;dialogWidth:300px ;dialogHeight:300px ;status:no ;scroll:no ;status=no;'); </script>", false);
Am using the below code to display the message details. Its work in all pages and it doesn't work in some places. The below script does't work when am using calendar render event.Please help me to fix this error..
My partial code is here:
finally
{
if (message != "")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "<script language='javascript'>alert('List : \\n" + message + "');</script>", false);
}
}
i think its may be because of no value in you 'message' variable. please try once by commenting the 'if' block/condition.
I have the following code, but the alert box is not displaying.
try
{
do something..
}
catch(Exception ex)
{
Response.Write("<script>alert('"+ex+"')</script>");
}
If I use this code, the alert box appears.
try
{
do some thing
}
catch (Exception ex)
{
Response.Write("<script>alert(\"an error occur\")</script>");
}
How can I display the exception variable in an alert box?
If you want to show the stacktrace:
Response.Write("<script>alert('"+ Server.HtmlEncode(ex.ToString()) + "')</script>");
or if you want only the message
Response.Write("<script>alert('"+ Server.HtmlEncode(ex.Message) + "')</script>");
Try something like
Response.Write("<script>alert('"+ex.Message+"')</script>");
Have a look at the class Exception Class
Dim message = New JavaScriptSerializer().Serialize(rs)
Dim script = String.Format("alert({0});", message)
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "", Script, True)
Please check whthr you r using update panel in that page.It may sometimes work if the update panel is there.
You need to be careful and properly escape the Javascript string you are generating ... Imagine there are single quotes in the Exception's message ...
Single-quotes (') need to be escaped (\')
Response.Write("<script>alert('"+ Server.HtmlEncode(ex.Message).Replace("'","\\'" ) + "')</script>");
This solved my problem:
string jscriptCustInfo = "<script type='text/javascript' language='javascript'>";
jscriptCustInfo = jscriptCustInfo + "alert('Dividend Posting Done, Batch No: "+lblBatch.Text+"');";
jscriptCustInfo = jscriptCustInfo + "</script>";
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", jscriptCustInfo, false);