call clientside javascript from asp.net c# page - c#

I have a c# asp.net page and an update function which will update the database. In this function I would like to call some client side javascript. I've read a lot about registering a start up script in page_load() but this is always trigger on page load (funny that!)
How would I register then call a script inside my update function? Triggered when a user clicks the "update" button. I have tried the following (inside my function)
protected void doUpdate(object sender, EventArgs e) {
string jScript;
jScript = "<script type=text/javascript>alert('hello');<" + "/script>";
ClientScript.RegisterStartupScript(GetType(), "Javascript", jScript);
}
but it isn't fired. Any ideas? Many thanks.
[update]
It's now working - the function looks like this
protected void doUpdate(object sender, EventArgs e) {
ScriptManager.RegisterStartupScript(this, GetType(),"Javascript", "cleanup();",true);
}
Cleanup() is the javascript function in my HTML. Thanks for the help guys :)

If the control causing the postback is inside an UpdatePanel you need to use
ScriptManager.RegisterStartupScript

You can't 'execute' client side scripts from the web server (the client knows who the server is, but not the other way around).
The only way to overcome this limitation is by a. create a long-polling process that requests something from the server, the server doesn't complete the request till it has something to return (then client side it makes another request).
What you are really looking for is websocket (duplex) enabled communication. You can check out alchemy websockets or SignalR (has a pretty nice library with dynamic proxy generation).
The reason why that 'script always works on Page_Load' is because it effectively injects your script tag into the html returned for the page requested.

Your Update button is likely using the standard ASP Button behavior, meaning it is type="submit" when it is rendered. Since that's the case, you can just use:
Page.ClientScript.RegisterOnSubmitStatement
Keep in mind that will register a script for every postback, not just the Update button. So, if you only want some javascript run on clicking Update, you would need to check if the EventTarget is UpdateButton.ClientID. Also, RegisterOnSubmitStatement always adds the <script> tags, so don't include those in the javascript statement.
An even easier solution, the ASP Button itself also has an OnClientClick property. This will run client-side code (javascript) when the button is clicked in the browser.

Related

Deciding whether javascript is disabled/enabled and execute a server side code [duplicate]

This question already has answers here:
redirect to another page if javascript is disabled [duplicate]
(5 answers)
Closed 2 years ago.
I've an aspx page which loads several images after detecting client's screen size. Here is how I do this:
In jquery code, I first detect user screen size, then depending on the size, I do some calculations to decide the number of images to be fetched from database. Then with the use of jquery ajax, I call up a web service which returns json response. Code picks up json and creates page.
Now, if user has disabled javascript, this approach doesn't work. Now I have to create page using c# code on code behind. The problem is, I can't detect if javascript is disabled from code behind (I think this is not possible). I do not want to display a button at the top says something "Javascript is disable in your browser. Please click here to display this page". I can put this button in noscript tags. But I do not want user have to click a button before seeing images on page.
What I want, if javascript is disabled, system should detect it and immediately run a function from code behind. (IN this case page size would be fixed and won't vary according to user screen) I can not use a hidden field or cookie to detect it since they both will need a postback before detecting javascript is diabled. (We know that js code can't run before any page life-cycle event).
Well I don't have much hope that my problem could be resolved, but still I want to give it a try. May be someone already have a solution. It would be extremely helpful if you could give your views or suggestion to change/update logic.
Any help would be greatly appreciated.
Thanks and Regards
Praveen
1.) Use JavaScript to set a cookie, and then test for that cookie using server-side scripting upon subsequent page views; deliver content appropriately.
How to detect if JavaScript is disabled?
2.) You can use <noscript> tag.
The <noscript> tag: can be used to provide an alternate content for users that have disabled scripts in their browser or have a browser that doesn’t support client-side scripting.
<noscript>
....
</noscript>
3.) Detect if JavaScript is enabled in ASPX
protected void Page_Load(object sender, EventArgs e)
{
if (Session["JSChecked"] == null)
//JSChecked -indicates if it tried to run the javascript version
{
// prevent infinite loop
Session["JSChecked"] = "Checked";
string path = Request.Url + "?JScript=1";
Page.ClientScript.RegisterStartupScript(this.GetType(), "redirect",
"window.location.href='" + path + "';", true);
}
if (Request.QueryString["JScript"] == null)
Response.Write("JavaScript is not enabled.");
else
Response.Write("JavaScript is enabled.");
}
Make default version without javascript and redirect to javascript version if javascript enabled. How to redirect if javaScript is disabled?

ASP.NET, ScriptManager, History Points and Dynamic Javascript

I have an ASP.NET user control that I want to write some dynamic Javascript to (basically a JQuery call to open an accordion node).
To complicate matters, I'm using history points. In a nutshell, I need to open a JQueryUI accordion based on a value in the history point data stored in the URL.
I've got the part that sets the history points working, and I can step through my code (below) as I navigate the history. The problem is, in this example, my script never renders on the page.
protected void uxScriptManager_OnNavigate(Object sender, HistoryEventArgs e)
{
if(!String.IsNullOrEmpty(e.State["activeTab"]))
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "xScript", "alert('Hello,world!');", true);
}
}
Am I doing something wrong?
Addendum
I've been tinkering, and it seems like my call to register the clientscriptblock works fine in other events...but in the Navigate event for the scriptmanager, I can't write new script out to the page. I'm thinking what I'm trying to do isn't possible...
From what I've found, it doesn't look like it's possible to write new client script out to a page - or change values in an existing script block - on the Navigate event. I'm noting this in case anyone else tries to do the same thing.
CORRECTION
I found out it is possible to do what I want!
I need to set the history point in an early part of the page lifecycle
I need to set the dynamic script in the RegisterStartupScript method for the page
(Ivan's post pointed me in the right direction, so I've flagged his post as the answer)
It looks like you need to add script by calling ScriptManager.RegisterStartupScript method to show elements on page:
ScriptManager.RegisterStartupScript(this, this.GetType(), this.ID,
""alert('Hello,world!');", true);

Forcing a postback

Is there a way to force a postback in code?
I'm looking to force the raising of a postback from a method in the c# code behind my asp.net web application.
You can try redirecting to same page.
Response.Redirect(Request.RawUrl);
A postback is triggered after a form submission, so it's related to a client action...
take a look here for an explanation:
ASP.NET - Is it possible to trigger a postback from server code?
and here for a solution:
http://forums.asp.net/t/928411.aspx/1
Simpler:
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "DoPostBack", "__doPostBack(sender, e)", true);
Here the solution from http://forums.asp.net/t/928411.aspx/1 as mentioned by mamoo - just in case the website goes offline. Worked well for me.
StringBuilder sbScript = new StringBuilder();
sbScript.Append("<script language='JavaScript' type='text/javascript'>\n");
sbScript.Append("<!--\n");
sbScript.Append(this.GetPostBackEventReference(this, "PBArg") + ";\n");
sbScript.Append("// -->\n");
sbScript.Append("</script>\n");
this.RegisterStartupScript("AutoPostBackScript", sbScript.ToString());
No, not from code behind. A postback is a request initiated from a page on the client back to itself on the server using the Http POST method. On the server side you can request a redirect but the will be Http GET request.
You can use a data-bound control like the Repeater or ListView, re-bind it to a list of control properties as needed, and let it generate the controls dynamically.
As an alternative, you can use Response.Redirect(".") to re-load the same page.
By using Server.Transfer("YourCurrentPage.aspx"); we can easily acheive this and it is better than Response.Redirect(); coz Server.Transfer() will save you the round trip.
You can manually call the method invoked by PostBack from the Page_Load event:
public void Page_Load(object sender, EventArgs e)
{
MyPostBackMethod(sender, e);
}
But if you mean if you can have the Page.IsPostBack property set to true without real post back, then the answer is no.

How do I generate JavaScript during an AJAX callback (postback) and then execute it on the browser?

In summary:
I have an ASP.NET web page that causes an AJAX postback to the server. When this event handler runs (in the code behind) it will generate some JavaScript that I then want to run in the client. Not sure how to achieve this.
In Detail:
I have an ASP.NET web page with multiple items displayed on the page.
As a "nice to have", I want to display either a green circle or a red cross next to each item (these differ depending upon each item). Since it isn't vital for the User to see these icons and also because it takes several seconds to work out which icon should be shown for each item, I want to perform this after the page has loaded, so in an AJAX callback.
My thought therefore was this. When creating the page, I would create both icons next to each object and create them with the style of "hidden". I would also make a note of each one's client ID.
Then, when the callback occurs, I fetch the necessary data from the database and then create a JavaScript function that changes the display for each of the icons I want to show from "hidden" to "visible".
I thought I could achieve this using the ScriptManager object.
Here's a very trivial version of my server side code (C#)
void AjaxHandler(object sender, EventArgs e)
{
// call to database
string jscript = "alert('wibble');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", jscript);
}
Obviously, here I'm just trying to get an alert to fire after the postback has occurred...in real life I'd have my JavaScript function to change the display of all the icons I want to display.
When I run this, the serverside code runs and yet nothing happens in the server.
I have also tried:
ScriptManager.RegisterClientScriptBlock()
Page.RegisterStartupScript()
Page.RegisterClientScriptBlock()
Page.ClientScript.RegisterStartupScript()
Page.ClientScript.RegisterClientScriptBlock()
but none of them work....
FireFox shows the following JavaScript error:
Error: uncaught exception: [Exception... "Node cannot be inserted at the specified point in the hierarchy" code: "3" nsresult: "0x80530003 (NS_ERROR_DOM_HIERARCHY_REQUEST_ERR)" location: "http://localhost/MyWebSiteName/Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=ctl00_RadScriptManager1_TSM&compress=1&_TSM_CombinedScripts_=%3b%3bSystem.Web.Extensions%2c+Version%3d3.5.0.0%2c+Culture%3dneutral%2c+PublicKeyToken%3d31bf3856ad364e35%3aen-US%3a3de828f0-5e0d-4c7d-a36b-56a9773c0def%3aea597d4b%3ab25378d2%3bTelerik.Web.UI%2c+Version%3d2009.3.1314.20%2c+Culture%3dneutral%2c+PublicKeyToken%3d121fae78165ba3d4%3aen-US%3aec1048f9-7413-49ac-913a-b3b534cde186%3a16e4e7cd%3aed16cbdc%3a874f8ea2%3af7645509%3a24ee1bba%3a19620875%3a39040b5c%3af85f9819 Line: 1075"]
Does anyone know if what I am trying to do is even allowed?
If not - what's my alternative?
Thank you
Since your script doesn't have enclosing <script> tags, you need to use this form of RegisterStartupScript:
ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", jscript, true);
You said your initial goal was:
The idea was that the page would load, data would be sent (AJAX) to the server. The server would then generate some JavaScript based upon this data and send that back to the page. That JavaScript would then run updating the page in a specific way.
Here's a way you can do that:
given:
<asp:ScriptManager runat="server" ID="scriptManager">
</asp:ScriptManager>
<script type="text/javascript">
function endRequestHandler(sender, args) {
var dataItems = args.get_dataItems();
for(var key in dataItems){
if(/^javascript:/.test(dataItems[key])){
eval(dataItems[key].substring("javascript:".length));
}
}
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
</script>
<asp:UpdatePanel runat="server" ID="pnl">
<ContentTemplate>
<asp:Button runat="server" ID="btnClick" Text="Click me!" OnClick="btnClick_Click" />
</ContentTemplate>
</asp:UpdatePanel>
You can create a click handler that does this:
protected void btnClick_Click(object sender, EventArgs e)
{
ScriptManager.GetCurrent(Page).RegisterDataItem(this, "javascript:alert('hello world!');");
}
What's happening is during the postback, the page request manager is sent a data item your code-behind. That data-item happens to be a javascript command. After the postback, the client side script manager's endRequest handler is checking for data items. Normally you'd want to see who those items are for, which is apparent by the key of the item (it's the client ID of the control that is the target of the data being sent). In your case, you could load this up with the javascript that you want to fire, tell yourself that it's a javascript because it's prepended, then dynamically evaluate the script.
So in this example, clicking the "Click Me!" button will generate a Hello World prompt whose script was actually created by the code-behind during the postback.
You'll have to be very cautious with this approach until you're comfy - I'd avoid references to "this"...
Happy coding.
B
Okay
The idea was that the page would load, data would be sent (AJAX) to the server. The server would then generate some JavaScript based upon this data and send that back to the page. That JavaScript would then run updating the page in a specific way.
Couldn't get that to work....
I got around this in the following way:
When the page loads, data is sent (AJAX) to the server. This processes the data and serialises the results updating a hidden text element, which goes back to the browser. Meanwhile, I have a JavaScript timer on the page that runs a JavaScript function that was generated when the page first loads. This function looks at the hidden text element. If that element has text (the result of the postback) then it shuts down the timer, deserialises the data and then works out how to update the page.

Can't get no javascript to execute on an ASP.NET user control

I'm trying to do the simplest thing, to show an alert popup through javascript from my code-behind of a user control (ascx.cs).
I've tried
protected void btnSave_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(btnSave, GetType(), "uniqueID", "alert('hello');", true);
}
as well as
Page.ClientScript.RegisterStartupScript(GetType(), "uniqueID", "alert('hello');", true);
but nothing seems to work for me. The control is located within an RadAjaxPanel (telerik) in an ASPX page.
I'm missing something obvious here. Any ideas what?
EDIT: The javascript is not injected into the html source as far as I can see. I look for the ID and the actual alert statement in the html.
Pass page's type to client script type parameter :
Page.ClientScript.RegisterClientScriptBlock(typeof(MyPage),
"myPostBackScript", script, true);
EDIT : Normally this code works, but I don't know how telerik's control effects the injected script. I think you should open HTML source of the page and try to find injected script. This will help us to solve your problem.
Ah, the problem was the Telerik RadAjaxPanel. I just had to set the EnableOutsideScripts to true on them, like so:
<telerik:RadAjaxPanel ID="ajaxpanel" runat="server" LoadingPanelID="ajaxLoadingPanel" EnableOutsideScripts="true">
And then I could use the following code:
ScriptManager.RegisterStartupScript(btnSave, GetType(), "uniqueID", "alert('hello');", true);
Do you have <form runat="server" in your page?
do you call if from onClienClick event of the button? whatever control you're using, make sure you're calling the js from a client-side event
also, take a look at this for ideas
EDIT
you cannot CALL js from the server, js is CLIENT-SIDE script. what you can do is to Register your script AFTER you do all the checking, and tie it to onload event. see this SO question for details
EDIT2
check out the last post on this page

Categories

Resources