Inject Javascript from asp.net code behind files - c#

Am I injecting this correctly?
string myScriptName = "EventScriptBlock";
string myScript = string.Empty;
//Verify script isn't already registered
if (!ClientScript.IsClientScriptBlockRegistered(myScriptName))
{
Response.Write('b');
myScript = "\n<script type=\"text/javascript\" language=\"Javascript\" id=\"EventScriptBlock\">\n";
myScript += "alert('hi');";
myScript += "\n\n </script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), myScriptName, myScript);
}
This is in my Page_Load, but I never see an alert and I have no JavaScript errors either.

You can use registerstartupscript instead of registerclientscriptblock!
RegisterStartupScript
When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM
RegisterClientScriptBlock
When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error
Difference between registerstartupscript and registerclientscriptblock
protected void Page_Load(object sender, System.EventArgs e)
{
string myScript = "\n<script type=\"text/javascript\" language=\"Javascript\" id=\"EventScriptBlock\">\n";
myScript += "alert('hi');";
myScript += "\n\n </script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myKey", myScript, false);
}

I have a feeling this is related to your asp.net/html markup.
Do you have a form tag like so in your .aspx file?
<form id="form1" runat="server">
....
</form>

Both RegisterStartupScript and RegisterClientScriptBlock will work.
Problem lies in myScript (string variable).In myScript variable you need to use alert variable only, as whenever you use this, script tag will be added automatically to your page's HTML at runtime. To check this right on your page and see the source of the page.
protected void Page_Load(object sender, EventArgs e)
{
string myScript = string.Empty;
//myScript = "\n<script type=\"text/javascript\" language=\"Javascript\" id=\"EventScriptBlock\">\n";
string registerKey = "alert('RegisterClientScriptBlock');";
myScript = "alert('RegisterStartupScript');";
Page.ClientScript.RegisterStartupScript(this.GetType(), "RegisterStartupScript", myScript, true);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "RegisterClientScriptBlock", registerKey, true);
}
Note: I have executed RegisterStartupScript first and than RegisterClientScriptBlock.But RegisterStartupScript alert will be executed at last, as it will be added at the end of the page.
RegisterClientScriptBlock will always be added at the starting of the page.

You should use RegisterStartupScript.

Related

call jQuery function from code behind at master page on page load

I am calling a jQuery function from code behind in my master page on page load, and it is returning this error:
ReferenceError: $ is not defined
Code Behind:-
protected void Page_Load(object sender, EventArgs e)
{
string script = "$(document).ready(function () {alert('hello'); });";
Page.ClientScript.RegisterStartupScript(this.GetType(), "load", script, true);
}
I also tried this jquery function :-
ScriptManager.RegisterStartupScript(Page, typeof(Page), "ShowProgressBar", "ShowProgressBar();", true);
but then getting the error "ShowProgressBar is not defined".
Try this,
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Function1", "yourFunction();", true);
You miss to load your jquery file add following script tag in header.
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>

Tekerik radwindow open and close issue

With the click event of a link button calling a server side method from Form1
Form1 aspx.cs page code:-
protected void lnkTakeAction_OnCommand(object sender, CommandEventArgs e)
{
if (e.CommandName == "duplicate")
{
//Some operations conditional
//If condition true
//call javascript method to call a javascript function to open a rad window
ScriptManager.RegisterStartupScript(this, typeof(System.Web.UI.Page), "ABC "ABCPopUp" + ID + "','Tag');", true);
}
}
Form1 aspx javascript code:-
function ABCPopUp(ID, Tag) {
var oWindow = window.radopen('XYZPage.aspx?ID=' + scoreMethodId + '&Tag=' + mode, 'rdWindowMapping');
oWindow.SetSize(600, 500);
oWindow.Center();
var titleBar = oWindow.GetTitlebar();
$telerik.$(titleBar).parent().hide();
return false;
}
Issue facing - The XYZPage is not opening.The same functionality works if I call the function ABCPopUp from javascript.But when I call from server side the form is not opening.Please give expert advice
Most likely, the script runs too early. You have two options:
use AJAX for the grid and do not include the RadWindow in the response
OR, use the Sys.Application.Load event to call your function: http://www.telerik.com/help/aspnet-ajax/window-troubleshooting-opening-from-server.html.

Scriptmanager not loading properly

I want to show a div after an action.
For now i will just use a button click event.
this is my jquery function:
function hideMessageBlock() {
$('.alert').delay(5000).fadeOut('slow');
}
i also tried this one:
$(document).ready(function(){
console.log('READY to animate');
function hideMessageBlock() {
$('.alert').delay(5000).fadeOut('slow');
}
});
in my code behind i have the following code:
protected void Button1_Click(object sender, EventArgs e)
{
alertSuccessBlock.Visible = true;
lbl_alertSuccessBlock.Text = "Animate this block with timeout!";
ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptManager1", "hideMessageBlock();", true);
}
in the aspx i have declared a scriptmanager right after the scripts i use (bottom of the page before form and body closure):
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
The Error that i am receiving is : ReferenceError: hideMessageBlock is not defined
The function is called before the whole jquery script is loaded (just guessing)
How can i resolve this issue?
I have already solved the issue. I had to move the function definition outside of the document.ready callback

Alert message on paging in gridview

I want to show an alert when user tries to do paging in gridview. I am using this script, but the alert pops up even if any of those buttons in the page is clicked in the page. I need to alert only when paging is clicked.
<script type="text/javascript">
function closeEditorWarning() {
return 'It looks like you have been editing something -- if you leave before submitting your changes will be lost.'
}
window.onbeforeunload = closeEditorWarning
</script>
Really appreciate any help on this.
Write an java script alert inside gridview_pageindexchanging() event to do this:
You can do this by using Script Manager as follows:
You have double script tags. Add the script tags yourself:
protected void grid_pageindexchanging(object sender, GridViewPageEventArgs e) {
string script = "<script type=\"text/javascript\">alert('abc');</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script);
}
Or let the method add it:
protected void grid_pageindexchanging(object sender, GridViewPageEventArgs e) {
string script = "alert('abc');";
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script, true);
}
Hope this helps..
Updated:
try including the following:
using System.Web.Script.Serialization
Updated 2:
Can you try this now:
string script = "alert('its working now!')";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "its working",script,true);
If jQuery is an option, set a CSS class on the pager and associate your script with the click event for that class.
Untested but probably in the right direction:
$('.myClass').click(function () { closeEditorWarning; });

from page *.aspx.cs call javascript function

I want to call a javascript function from my codebehind.
In my button click event handler I have:
protected void load_data_Click(object sender, EventArgs e)
{
if (dt.Rows.Count == 1)
{
BindDl();
}
else
{
//if dt.rows.count! = 1 I want to call a JavaScript function where be one alert! how to do?
}
}
This page will be helpful for you
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
Type cstype = this.GetType();
String csName = "MyAlertFunction";
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csName))
{
String jsFunction = "yourFunctionHere()";
cs.RegisterStartupScript(cstype, csName, jsFunction, true);
}
user scrip manager
ScriptManager.RegisterStartupScript(this, typeof(string), "SHOW_ALERT", "alert('')", true);
where in place of alert you can put your javascript code, next argument true puts in script tags automatically so you dont have to write them.

Categories