I am trying to call a JavaScript function from my ascx control code behind in the catch block.
I have tried the below two ways but they don't seem to work.
Page.ClientScript.RegisterClientScriptBlock(typeof(string), "script", "test();", true);
ScriptManager.RegisterStartupScript(Page, GetType(), "err_msg", "alert('error');", true);
The function is called if I place the code Under "PageLoad" but doesn't get called when placed in catch block.Should I do any different to call a JavaScript function from catch block. Please suggest.
Thanks
Have you tried this?
Page.ClientScript.RegisterStartupScript(typeof(string), "script", "test();", true);
I cant recall off the top of my head if that is equivalent to the ScriptManager option in the question.
Also you need to make sure that the "script key" value you are passing in is unique otherwise asp.net will discard all but the first instance of the registered script with the same key.
might want to try this:
.cs
public String ScriptToRun = "test();";
.aspx
$(document).ready(function() {<%=ScriptToRun %>}); //or you can register event to document mannually
Remember that whatever you done in backend is going to generate HTML, Css& javascript to browser.
update:
I tried the following code, it works in my case. could you please provide more detail?
.cs
public String script = "";
protected void Page_Load(object sender, EventArgs e)
{
throwExcep();
}
private void throwExcep()
{
try
{
throw new NotImplementedException();
}
catch (Exception e)
{
script = "console.log('exception throws from backend message: ["+e.Message+"]')";
}
}
.aspx:
<script>
$(document).ready(function(){
<%=script %>
});
</script>
Javascript does not like at all special characters and NewLine (\r\n) characters. Replace all of those and it will work.
Example:
string test = msgError.Replace("'", "");
test = Server.HtmlEncode(test).Replace(Environment.NewLine, "<br />");
Page.ClientScript.RegisterStartupScript(
typeof(string),
"MyKeyCatch",
//script,
"showErrorMessage('"+test+"');",
true);
What is the catch block for and where is it?
If code in a catch block is executed it usually means that something failed, maybe that failure also is the reason the JS call does not go through.
Related
I have made previous posts about my custom visualization not working in Spotfire:
https://stackoverflow.com/questions/25390099/awesomium-javascript-handler-being-called-indefinitely
Returning value to C# function from Javascript not working in Awesomium
and I have finally narrowed it down to the offending line.
In my document, I load a source script:
<script src="http://d3js.org/d3.v3.min.js"></script>
This seems to break my entire custom visualization; it infinitely tries to reload the page, from what I've seen. Here is my C# code:
private void WebViewOnDomReady(object sender, EventArgs eventArgs)
{
webView.DomReady -= WebViewOnDomReady;
webView.CreateObject("jsobject");
//webView.SetObjectCallback("jsobject", "callNETNoReturn", JSHandler);
webView.SetObjectCallback("jsobject", "callNETWithReturn", JSHandler);
//webView.ExecuteJavascript("myMethod()");
var result = webView.ExecuteJavascriptWithResult("myMethodProvidingReturn('foo')");
MessageBox.Show("Stuff:" + result.ToString());
}
private void JSHandler(object sender, JSCallbackEventArgs args)
{
var result = webView.ExecuteJavascriptWithResult("myMethodProvidingReturn('foo')");
MessageBox.Show(result.ToString());
MessageBox.Show("Got method call with no return request");
}
And here is my Javascript code:
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
function myMethod() {
document.write("In myMethod, calling .NET but expecting no return value.<br/>");
jsobject.callNETNoReturn();
}
function myMethodExpectingReturn() {
document.write("In myMethodExpectingReturn, calling .NET and expecting return value.<br/>");
var returnVal2 = jsobject.callNETWithReturn("foo");
document.write("Got value from .NET: " + returnVal2 + "<br/>");
}
function myMethodProvidingReturn(whatToReturn) {
var returnVal = whatToReturn + "bar";
document.write("Returning '" + returnVal + "' to .NET.");
return returnVal;
}
</script>
Interestingly enough, the HTML loads fine if I don't try and call a Javascript function and get the return value in C#. However, when I try to return the result of the JS function and print it in C#, including the script src line breaks my entire code; it infinitely returns a blank message judging from the MessageBoxes that I have set.
This is completely baffling me, as it seems to mean that the HTML is being loaded over and over again. Setting the script src tag, for some odd reason, causes this infinite loop.
What exactly is happening?
Thanks
I need a code segment to call a javascript function recordInserted() which shows up an alert, from my following code behind method,
protected void add_Click(object sender, EventArgs e)
{
String gradename = txt_gradename.Text;
int allocatedclasses = Int32.Parse(txt_allocatedclasses.Text);
String headid = txt_head_id.Text;
int numberofstudents = Int32.Parse(txt_numberofstudents.Text);
db = new DBConnection();
db.getConnection();
db.executeUpdateQuery("INSERT INTO Grade (GradeName,AllocatedClasses,GradeHeadID,NumberOfStudents) VALUES ('"+gradename+"','"+allocatedclasses+"','"+headid+"','"+numberofstudents+"')");
//I Need to call it from here before redirecting
Response.Redirect("AdminReferenceGradeAdd.aspx");
}
Please helpp me with this.
I have tried the following but never worked,
Page.ClientScript.RegisterStartupScript(this.GetType(),"Call my function","recordInserted()",true);
This will never work .. beacuse you are saying to redirect.
when you say Response.Redirect every thing which you have prepared to send is not sent,instead response is redirect to a new page.So your client script never reaches to browser.
you can use it like this :-
Page.ClientScript.RegisterStartupScript(this.GetType(),"Call my function","recordInserted();window.location.href='wwW.google.com'",true);
use window.location.href to redirect to your page("yourpage.aspx').
Try this:
ClientScript.RegisterClientScriptBlock(typeof(Page), "Call your function", "recordInserted()", true);
Or try calling Javascript function after a second:
ClientScript.RegisterClientScriptBlock(typeof(Page), "Call your function", "setTimeout('recordInserted()', 1000)", true);
So, I am dynamically generating jQuery using C# and sending it to the webpage.
The problem is it appears to be generating correct jQuery according to the file and according to Js Fiddle but it does not actually work on the page.
The jsFiddle is here http://jsfiddle.net/ER2hE/
Now I looked up how to send javacript to the website. It should work like this.
http://msdn.microsoft.com/en-us/library/bb359558.aspx
and my code which does that is this method
private void sendScript(string script)
{
const string someScript = "alertMe";
//send the built script to the website.
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), someScript, script, true);
}
This is super simple it has worked for other pieces of code calling. But it has not for this instance.
The code that calls it is this in my C#
private void populateGroups()
{
//this generates correct javascript according to the file and JS fiddle but unfortunately doees not work.
string splitme = "USE ACES SELECT GroupName, GroupID FROM PrimaryGroup ORDER BY GroupName";
DataTable dt = fillDataTable(splitme);
string script = "";
foreach (DataRow dr in dt.Rows)
{
//add the locations to the <select> box
script += " $('#groupList').append('<option value=\" " + dr.ItemArray[1].ToString() + " \"> " + dr.ItemArray[0].ToString() + " </option>'); ";
}
sendScript(script);
JSErrorLog(script, "GROUPS");
}
The whole thing is being called on startup
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack == false)
{
populateMakes();
populateLocation();
populateGroups();
}
}
The jQuery its generating also works in JSFiddle I am pulling this from a method that writes the javascript it generates in a method calling here is the fiddle JSErrorLog.
http://jsfiddle.net/ER2hE/
Oh and my html in my aspx file looks like this
<div class="row2">
<span>Group</span>
<select id="groupList" multiple="multiple" onclick="setGroups()" class="normalsize">
</select>
</div>
I believe that is everything. I just want my stuff to work. I am willing to post any additional code, just ask. If you have an idea as to why its not working, let me know.
When does it actually execute that code? Before or after the element with id "groupList" exists in the DOM? My guess is before.
Solution? Wrap your code inside a document.ready handler.
jQuery(function($) {
$('#groupList').append('<option value=" 46 "> AC Units </option>');
// etc etc
});
Return simple string js code. And run it with eval()
I have a class. There is only deleteRecord function
protected virtual void DeleteRecord
{
if(..)
{}
else(..)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "<script language='javascript'>alert('Are you sure?')</script>", true);
}
}
I want to show javascript message. But I think I made a mistake.
How can I do it?
You've added true to the last parameter on Page.ClientScript.RegisterStartupScript which is addScriptTags. See http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx
Therefore you have essentially added <script> within a <script>
Try this:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Are you sure?')", true);
Also ensure the key parameter is unique to the page. If you already have a StartupScript with the key of "Alert" then this can also stop it from calling the JavaScript code.
I created this static class that I can call from any web page: (I use AJAX Toolkit for script manager, but you can use the default one in ASP.NET as well)
public static class ClientJS {
public static void send(string js) {
Page page = HttpContext.Current.Handler as Page;
ToolkitScriptManager.RegisterStartupScript(page, page.GetType(), Guid.NewGuid().ToString(), "setTimeout(function(){" + js + "},1);", true);
}
}
Use it like so:
ClientJS.send("alert('Are you sure?');");
I want to call javascript function from User Control using C#. For that i am trying to use
ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", "javascript:ShowPopup('Select a row to rate');", true);
but it is not working for me. This works fine on the page. Can some one help me out how can i call javascript function at runtime using C#.
Thanks,
Try this.GetType() instead of typeof(string):
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertbox", "ShowPopup('Select a row to rate');", true);
The following is taken from working code, showing script being registered to fire from an asynchronous postback in an UpdatePanel.
ScriptManager.RegisterStartupScript( this.upnl, this.upnl.GetType(), Guid.NewGuid().ToString(), "alert('test');", true );
If your code is not executed from inside an UpdatePanel, it still should not be typeof(string); you should use the type of some container (typically the control itself).
Type: The type of the client script block. This parameter is
usually specified by using the typeof
operator (C#) or the GetType operator
(Visual Basic) to retrieve the type of
the control that is registering the
script.
Im not sure if this is the best way to do it but for my user controls that use javascript i have a public string property on the user control and register it in the page.
// sudo code
eg.
UserControl
{
public bool CustomBool
{
get
{
//logic
return value;
}
}
public string Javascript
{
get { return "javascript...."; }
}
}
in page
{
page load()
{
if (Usercontrol.CustomBool)
{
ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", UserControl.Javascript, true);
}
}
}
The downside for this is you have to remember to register the scripts on the page. it does work though
Try it without the "javascript:" in the script string:
ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", "ShowPopup('Select a row to rate');", true);
I find that the string given is embedded literally, so it's necessary to enclose it in a suitabie <script type='text/javascript' language='javascript'> and </script>