I want to show exception in alert box in asp.net 4. But it is not showing any alert.
I tried these solutions -
try{// my code}
catch (Exception ex)
{
//Response.Write("<script>alert('" + Server.HtmlEncode(ex.Message) + "')</script>"); // Not Working
//Response.Write("<script>alert('" + ex.Message + "');</script>"); // Not working
// Response.Write("<script>alert('" + Server.HtmlEncode(ex.ToString()) + "')</script>"); // Not working
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "done", "alert('Error Occured.');", true); // Only this is working.
}
Please suggest any solution to this where I am going wrong.
Thanks and regards,
Rizwan Gazi.
Normally Response.Write(); always works. But as you said its not working than
Try this :
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "done", "alert('" + ex.Message.Replace("'", "") + "');", true);
Let me know if it solves your issue.
Related
I would like to call javascript function in case something in my code behind would happen.
If it is like the code below it works fine after postback alert windows shows and says it correctly. But in case I remove the comment from else block none of those two scripts in else block will happen?
Is there any limit on how many of these action could I make from codebehind?
if (condition) {
if (condition2) {
var message = "It happened !";
Page.ClientScript.RegisterStartupScript(this.GetType(), "yep1", "alert('" + message + "')", true);
}
} else {
var msg = "It does not work like that";
Page.ClientScript.RegisterStartupScript(this.GetType(), "nope1", "alert('" + msg + "!')", true);
//Page.ClientScript.RegisterStartupScript(this.GetType(), "nope2", "alert('" + msg + "')", true);
}
This way it will work. As the name of the function says, it register the startup script so you are changing it instead of inserting 2. In this way it will do both ^^
if (condition)
{
if (condition2)
{
var message = "It happened !";
Page.ClientScript.RegisterStartupScript(this.GetType(), "yep1", "alert('"+message+"');", true);
}
}
else
{
var msg = "It does not work like that";
Page.ClientScript.RegisterStartupScript(this.GetType(), "nope1", "alert('"+msg+"!'); alert('" + msg + "');", true);
//Page.ClientScript.RegisterStartupScript(this.GetType(), "nope1", "alert('"+msg+"!')", true);
//Page.ClientScript.RegisterStartupScript(this.GetType(), "nope2", "alert('" + msg + "')", true);
}
I am trying to display a string along with the message.But i get an error.
str1 is a value retrieved from a table
the code is
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect", "alert('Welcome'); window.location='" +
Request.ApplicationPath + "#';", true);
but i want to display it as follows
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect", "alert('Welcome '" + tbEmail.Text + "''); window.location='" +
Request.ApplicationPath + "#';", true);
I'm just a beginner,any help is appreciated ,thank you
Is there any way I can modify "alert('error !') part of the script manager to include message in the label below? I don't want to use the label for that, just display database error in the pop up window. I tried adding it with + but either it doesn't work or the pop up isnt displayed at all. Thanks
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('error !') ", true);
lblError.Text = "A database error has occured. <br /> <br />" +
"Message: " + ex.Message;
It doesnt like this:
<!-- all the links for datetime picker -->
<link rel="stylesheet" type="text/css" href="../style/jquery.datetimepicker.css"/ >
<script src="../Scripts/jquery.js"></script>
<script src="../Scripts/jquery.datetimepicker.js"></script>
<script>
$(function() {
$( "#datetimepicker" ).datetimepicker();
});
</script>
You can create a javascript function and call it to change the text of any label you want.
My suggestion is:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", " changeLabel('" + ex.Message + "', '" + lblError.ClientID +"'); alert('error !'); ", true);
And the javascript function :
function changeLabel(text, id){
$("#"+id).val(text);
}
try
{
..
}
catch(Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Database error ocurred : "+ ex.Message.ToString()+"')", true);
}
Unfortunately you cannot add HTML tag in javascript alert message.
Simple Alert
Make sure you strip out the single quote ' in ex.Message.
try
{
throw new Exception("test");
}
catch (Exception ex)
{
string message = string.Format("alert('A database error has occured. {0}');",
ex.Message.Replace("'", ""));
ScriptManager.RegisterStartupScript(this, this.GetType(),
"alert" + UniqueID, message, true);
}
jQuery Dialog
However you can use jQuery Dialog if you want to insert HTML.
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<div id="dialog" title="Basic dialog">
<div id="dialog-text"></div>
</div>
try
{
throw new Exception("This is an error message.");
}
catch (Exception ex)
{
string message = string.Concat("$(function () {$('#dialog').dialog(); " +
"$('#dialog-text').html('A database error has occured. " +
"<br /> <br />", ex.Message, "');});");
ScriptManager.RegisterStartupScript(this, this.GetType(),
"alert" + UniqueID, message, true);
}
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "<script language='javascript'>alert('A database error has occured.\n\n"+ ex.Message +"' );</script>", true);
window.onerror = function(type, file, line){
if(type) {
console.log(type);
}
if(file) {
console.log(file);
}
if(line) {
console.log(line);
}
}
this code returns "Script error" when there is an error at some of the .js files. I need the type, file and line of the error. How can I get it?
When window throws error this script works perfect but it is not the same when there is error in the .js file.
I know that these things I can find on the console but imagine that I don't have one and i cannot install.
window.onerror = ErrorLog;
function ErrorLog (msg, url, line) {
console.log("error: " + msg + "\n" + "file: " + url + "\n" + "line: " + line);
return true; // avoid to display an error message in the browser
}
The post of Cryptic "Script Error." reported in Javascript in Chrome and Firefox should answer your "Script Error." problem. Namely it is probably caused by "Same origin policy".
Though I am still looking for why webkit will give me "undefined" file name and "0" line number for uncaught exception.
Here's what I use to capture errors. I have it request an image whose url points to a server side script.
function logJSErrors(errObj) {
if (!errObj || !errObj.lineNumber || errObj.lineNumber == 0) {
return; // can't use it any way.
}
if (window.location && window.location.toString().indexOf('rfhelper32.js') >= 0) {
return; // ignore the stupid Norton/Firefox conflict
}
var img = new Image();
img.src = "/jserror?m=" + encodeURIComponent(errObj.message) +
"&location=" + encodeURIComponent(window.location) +
"&ln=" + encodeURIComponent(errObj.lineNumber) +
"&url=" + encodeURIComponent(errObj.fileName) +
"&browser=" + encodeURIComponent(errObj.browserInfo);
}
window.onerror = function (msg, url, line) {
logJSErrors({ message : msg,
lineNumber : line,
fileName : url,
browserInfo : window.navigator.userAgent
});
// if a jquery ajax call was running, be sure to make the spinning icons go away
if (jQuery) {
try {
jQuery.event.trigger("ajaxStop");
} catch(e) {/* do nothing */
}
}
};
int i = Convert.ToInt32(Session["sayfaTuru"]);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", "f2(" + i + ")", true);
function f2(i) {
if (i == 1) {//CariKartHareketleri
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.location.href = window.opener.location.href; //çağıran sayfayı yeniliyor
}
else if (i == 2) {//islemler
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.__doPostBack('GridRefreshPanel.ClientID', '');
}
else if (i == 3) {//hizmet listesi
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.__doPostBack('GridRefreshPanel.ClientID', '');
}
}
it says i is undefined when I debug the code in f2(i).What am i doing wrong?
EDIT: I learned many things from this problem, but I still do not have an answer.I tried every idea given in the answers but i is still undefined...
EDIT: I still have no solution for undefined reasons :), but the answer I accepted would normally be my solution.
Have you tried debugging the server-side code to see if
int i = Convert.ToInt32(Session["sayfaTuru"]);
is giving you what you want in the first place?
Well seeing as how the above has been checked, I went ahead and created my own test, and it worked just fine. Here's the test I used:
JS:
<script type="text/javascript">
function f2(i, hiddenFieldId, updatePanelId) {
console.log(i + ', "' + hiddenFieldId + '", "' + updatePanelId + '"');
var hiddenField = window.opener.document.getElementById(hiddenFieldId);
switch (i) {
case 1: //CariKartHareketleri
hiddenField.value = "hello world 1";
window.opener.location.href = window.opener.location.href; //çağıran sayfayı yeniliyor
break;
case 2: //islemler
hiddenField.value = "hello world 2";
window.opener.__doPostBack('' + updatePanelId + '', '');
break;
case 3: //hizmet listesi
hiddenField.value = "hello world 3";
window.opener.__doPostBack('' + updatePanelId + '', '');
break;
default:
alert("error");
break;
}
}
</script>
C#:
Session["sayfaTuru"] = 2; // initialize for testing purposes
int i = Convert.ToInt32(Session["sayfaTuru"]);
string script = string.Format("f2({0}, '{1}', '{2}');",
i.ToString(),
this.HiddenField1.ClientID,
this.GridRefreshPanel.UniqueID);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", script, true);
console.log Output:
2, "HiddenField1", "GridRefreshPanel"
ClientScript.RegisterStartupScript takes a script definition, not an invocation.
Since you want to define the function externally, use this method instead:
ClientScript.RegisterClientScriptBlock(this.GetType(), "RefreshOpener", "MyJavaScriptFile.js", true);
To execute the JavaScript function f2 with parameter Session["sayfaTuru"] on button click, use the following (not tested):
In Page_Load, add the JavaScript file which contains the definition for f2:
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(...);
// Do other stuff
}
Then add the actual button click listener which will invoke f2:
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="f2(<%=Session['sayfaTuru']%>);" />
I think you may be getting an Exception thrown in your code-behind. You're trying to concatenate strings, but i is an integer. Try this instead:
int i = Convert.ToInt32(Session["sayfaTuru"]);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", "f2(" + i.ToString() + ")", true);
Though I would actually prefer to use String.Format:
int i = Convert.ToInt32(Session["sayfaTuru"]);
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", String.Format("f2({0})", i), true);