ASP.NET, ScriptManager, History Points and Dynamic Javascript - c#

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);

Related

Setting Content in RadEditor

I have visited the Telerik's website and viewed their demos etc...
But I am having problems trying to load content (html) in the RadEditor.
I have a Button_Click event where I get my html string and then set it to the RadEditor. The RadEditor is inside a RadWindow and only becomes visible when the button is clicked.
protected void btnSubmitHtml_Click(object sender, EventArgs e)
{
RadEditor1.Content = "<p>hello there</p>";
RadWindow1.Visible = true;
}
This doesn't show the html inside the RadEditor for some odd reason. I suspect it is the page life cycle that is involved with this problem.
Are there any suggestions to solve this?
I have encountered this problem multiple times and never found a "Proper" resolution.
However, a great work around is to simply set the content from the clientside via injected script. The end result is the same, and if you can tolerate the 10 millisecond delay, worthy of consideration.
EDIT after comment requested reference
Basically all you need to get an instance of the editor using ASP.NET WebForms $find function. That takes the html ID of the root of the rendered object and returns the client side viewModel if one exists.
The $(setEditorInitialContent) call at the end assumes that jQuery is present and delays the execution of the function till page load.
<telerik:radeditor runat="server" ID="RadEditor1">
<Content>
Here is sample content!
</Content>
</telerik:radeditor>
<script type="text/javascript">
function setEditorInitialContent() {
var editor = $find("<%=RadEditor1.ClientID%>"); //get a reference to RadEditor client object
editor.set_html("HEY THIS IS SOME CONTENT INTO YOUR EDITOR!!!!");
}
$(setEditorInitialContent);
</script>
Take a look here to see how to get a RadEditor to work in a RadWindow: http://www.telerik.com/help/aspnet-ajax/window-troubleshooting-radeditor-in-radwindow.html.
Said shortly, here is what you need to have in the OnClientShow event of the RadWindow:
function OnClientShow()
{
$find("<%=RadEditor1.ClientID %>").onParentNodeChanged();
}
To edit Html code only you can add -
EnableTextareaMode="true"
Add this property to the RadEditor.
I suspect that the way the control tries to interpret the html might be one of the problems. The other thing that may be causing this problem is the page life cycle.

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?

Submit a form from code behind

I'm having trouble implementing a functionality on my c#/asp.net app.
I have a form with a RadioButtonList and a submit button.
The RadioButtonList is generated on Page_Load() from a list of objects I retrieve from the database.
I would like to automatically submit the form if there is only 1 object in the list.
I have access to my Form object, to the submit button etc... but I can't seem to find a solution (in the end I'm looking for a kind of form.Submit() ) method.
Does anyone have an idea of how I could do this ?
Thanks in advance !
EDIT >> Here is the code :
.aspx : http://pastebin.com/0E6T7dqH
.aspx.cs : http://pastebin.com/54payZJP
EDIT2 >>>
As it seems there is no way to do what I wanted to do at first, I ended up using a session variable with a response.redirect()
Source :
http://dotnetslackers.com/Community/blogs/haissam/archive/2007/11/26/ways-to-pass-data-between-webforms.aspx
Post happens in the client side. As in Page_Load you are currently executing in the server side, just call the code you want to execute on post.
Edit: For actually going to another aspx
public void Page_Load(object sender, EventArgs e) {
if(!IsPostback && OnlyOneItem) {
Server.Transfer("TheOtherPage.aspx");
}
}
Server.Transfer will maintain the entire request, so your post data will be available.
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.transfer.aspx
Try something like this
In your Page_Load
if(!IsPostBack)
{
if(check for only one object)
{
//your submit code
}
}
I actually had to do something similar, once. Here is a way you can do it.
Asp.Net buttons have a property called PostBackUrl, and it does exactly what you would expect - it controls where the form will post if you click the button.
You can also use the RegisterStartupScript function to render javascript on the page.
Now, with these two pieces, you can achieve your goal.
if(!IsPostBack)
{
if(results == 1)
{
button.PostBackUrl = "next page's url"
//Register script to click the button using RegisterStartupScript
}
}
Now, having shown you this, I will warn you it may not make for the best user experience. When I did it, it was for a very specific case that had no other solution. The page will actually post back to the user, and they will see the page for a moment before the javascript to click the button takes effect. Additionally, when you set a button's PostBackUrl, that means that when it is clicked, your entire form will be posted to the page specified. The code behind for the current page will not fire at all, so if you have any validation, it won't run.
There's nothing wrong with letting the user click the button to submit the form even if they only have one choice. In my experience, users like to feel like they are in control on the system; they don't like it when pages just do things without their input.
Also, there is not really anything wrong with putting the information the next page needs into the session or even a database table, and using Response.Redirect. It's a fairly common practice and works reliably in most scenarios.

call clientside javascript from asp.net c# page

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.

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