Call Javascript from code behind after partial postback - c#

I have a RadTreeView in a UserControl that is in an UpdatePanel and opens in a jQuery popup window. A button within the control raises a click event that is picked up by the containing page and results in the user control adding a new node to the RadTreeView from the code behind of the user control. Once this happens I want to then call a JavaScript function (that loops through all nodes and sets their visibility based on a filter string). Ideally I want to set this script call from the same function within the user control.
I have tried the following from code behind of the user control
ScriptManager.RegisterClientScriptBlock(
this,
this.GetType(),
"filter",
"filterItems('" + this.RadTV.ClientID + "','" + this.txtFilter.Text + "');",
true );
I have also tried something similar from the code behind of the parent page and registered the Script Block with the appropriate UpdatePanel.
In both cases, the Script is never called.
Any ideas?
Cheers
Stewart

You need handler for doing this.
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandle);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandle);
function beginRequestHandle(sender, Args) {
//Do something when call begins.
}
function endRequestHandle(sender, Args) {
Yourfunction();//Call your function here
}
</script>

Related

RegisterStartupScript in ButtonClick event of UserControl

I have a usercontrol with a form and a button. In the code behind of the button's click event, I save the data from the form to the database. After the save is successfully saved, I'd like to pop up a javascript alert. I've tried the following:
Control Caller = this;
ScriptManager.RegisterStartupScript(Caller, Caller.GetType(), " ",
#"<script language=javascript>alert('Asset successfully saved');</script>", true);
This doesn't work. What am I doing wrong, or even how do I debug this?
It is because you have set the addScriptTags to true and you are also trying to add your own script tags in the js code. Set this value to false and try again or remove the script block tags in your js. You can find out more details on msdn page.

How do I fire a aspx script when a dynamically added button is clicked?

Here is the context:
I am building a .aspx page that allows the user to administrate some xml documents we have on our server. The page content is loaded using AJAX, so buttons and forms are dynamically added to the document.
If I had static buttons that I was creating within the .aspx page before it loads on the client's machine, I could attach an event to it very easily. However, I'm dynamically adding and removing buttons and forms on the fly, using jQuery.
Here is a simplified example:
In the following jsFiddle, I'm pretending that the html document contains the following script:
<script language="C#" type="text/C#" runat="server">
void SaveAllChanges(Object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
clickedButton.Text = "foobar";
}
</script>
And that I have a javascript file that contains the following:
$('button.buttonGenerator').click(function() {
$('.buttonContainer').append(
'<button onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
});
Obviously the buttons I am creating can not run the function SaveAllChanges with the way it is now. I added the onclick attribute to show what I needed to happen, in a pseudo-code kind of style.
How can I make it so that dynamically added buttons can run the C# method I have defined within the script tag at the top of the document?
Here is the jsfiddle: http://jsfiddle.net/2XwRJ/
Thanks.
You can give all buttons that must save changes a common class (e.g. class="ajaxButton") and have one jQuery method that responds to click events on elements matching that class (use live so that updates to the DOM are reflected).
$("button.ajaxButton").live("click", function(){
// Perform your Ajax callback to run server-side code
});
What you need to do is use something like ..
$(document).ready(function() {
$('button.buttonGenerator').click(function() {
$('.buttonContainer').append(
'<button id="#dynamicCommentButton" onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
});
$(document).on('click', '#dynamicCommentButton', function() {
alert($(this).attr('id'));
});
});
You are not going to be able to add the buttons like you have it there as this code here is just adding it as an HTML DOM element and the onclick attribute will be the on the client element. As a result clicking the button will try fire a SaveAllChanges javascript function
$('.buttonContainer').append(
'<button onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
What would be best would be to create that SaveAllChanges function in javascript and then you can handle it from there. Two of the ways I see you being able to do this are:
Have a http endpoint setup (script service, web api or just posting to a page) that you call using Ajax from your javascript. You can then pass through any needed arguments.
You could have a hidden element and hidden button on the page so that when the javascript is called it populates any arguments you need and then clicks the hidden button and posts the page back.
Personally I would choose the first approach from a user experience stand point as the page will not be posting back each time. I have used something similar to the second approach and it works fine but just feels very clunky.

Can I move a div using javascript and retain its postback ability?

I've got a list of checkboxes and an ImageButton with an OnClick event in my page, clicking the ImageButton performs a postback and runs the OnClick event fine
The trouble is that I want to move the div to be the first child of the <form> so that I can make it appear in a modal window - I've done this using the prototype.js code...
document.observe("dom:loaded", function() {
if ($$('.CheckboxListContainer').length>0) {
var modalShadow = document.createElement('div');
modalShadow.setAttribute( "class", 'MyFormModalShadow' );
modalShadow.style.width = document.viewport.getWidth() + 'px';
modalShadow.style.height = document.viewport.getHeight() + 'px';
var modalDiv = document.createElement('div');
modalDiv.setAttribute( "class", 'MyFormModal' );
var checkboxesDiv = $$('.CheckboxListContainer')[0];
checkboxesDiv.remove();
modalDiv.appendChild( checkboxesDiv );
$$('form')[0].insert( {top: modalShadow} );
$$('form')[0].insert( {top: modalDiv} );
Event.observe(window, "resize", function() {
if ($$('.MyFormModalShadow').length>0) {
var modalShadow = $$('.MyFormModalShadow')[0]
modalShadow.style.width = document.viewport.getWidth() + 'px';
modalShadow.style.height = document.viewport.getHeight() + 'px';
}
});
}
});
... which works fine, but the ImageButton is no longer triggering my OnClick event on postback.
Is there a way to move my div around in the DOM and retain its postback abilities?
Quick answer, yes. Long answer below:
If you're talking ASP.NET WebForms, does your form have the runat="server" attribute and an id? If you're using standard HTML, are the method and action attributes set on the form?
When you look at the HTML source in your browser, if the form looks like: <form action="/your_post_back_page.html" method="post">, then that's all good. Inspect the form with FireBug after the modal dialog has been added, see if it is INSIDE the form tags. If so, that's good.
Do your check boxes <input type="checkbox" /> have a name attribute set? Is your image button <input type='submit' /> or is it a <button>?
If these conditions are met, then there is probably a JavaScript event (a function) wired to your button that is returning false and/or swallowing the postback. JavaScript onclick events generally need to return true to submit a form. Is there any output in your browser's error console?
Personally, I find more and more that pure HTML (by way of ASP.NET MVC) beats the pants off old school ASP.NET WebForms, and jQuery has, in my experience, a far nicer feel than prototype. Using jQuery templates to create a modal dialog would be easy. Can you swap libraries?
First of all, i am not very clear why you need to move the element to be the first child of the form to make it modal. You can make any div modal no matter where is the position in the form. The most important think is controlling the absolute positioning properly.
Each postback gets triggered by a __DoPostBack() javascript function, so you should not have any issues with moving the control around, unless you changed the id of the control.
One possible solution to your problem is calling the __DoPostBack() function from your client code in document.ready, and that way you have full control over the form submission.

dynamic Javascript in asp.net

well. The problem i'm facing is i have my own custom control and i do a query , get records and dynamically add html controls to the page based on the data.
Now there's the problem of adding some dynamic javascript
I do this with the help of literal controls.
<asp:Literal runat="server" ID="latEventToolTipJqueryScripts"></asp:Literal>
This works like a charm
<script language="javascript" type="text/javascript">
// <![CDATA[
Sys.Application.add_load(WireEvents_<%=this.ID%>); // fix wiring for .NET ajax updatepanel
$(WireEvents_<%=this.ID%>); // handle page load wiring
function WireEvents_<%=this.ID%>() {
<asp:Literal runat="server" ID="latEventToolTipJqueryScripts"></asp:Literal>
}
// ]]>
</script>
I add the literal text dynamically from code behind.
However, when placing the control in an updatepanel, the postbacks don't update the script.
EDIT: The Sys.Application.add_load rewires the necessary functions just fine with the updatepanel. The problem is that the script that needs to be in place of the literal, doesn't update when in an updatepanel.
I've tried the ClientScript.RegisterStartupScript but it has the same effect as with the literal control trick. Any help?
---------------------------SOLVED (tnx to Pranay Rana)----------------------------------
Got rid of the literal in the ascx side. as well as the Sys.Application.add_load
now it's only in the code behind. The thing that was throwing me off was the JQuery thing.
this.strBuilderJS.Append( "<script language='javascript' type='text/javascript'>" +
"$(WireEvents_" + this.ID + ");" +
"function WireEvents_" + this.ID + "(){"+
" alert('stuff');");
this.strBuilderJS.Append( "}</script>");
and then
ScriptManager.RegisterStartupScript(this, this.GetType(), "strBuilderJS", strBuilderJS.ToString(), false);
Make use of ScriptManager.RegisterStartupScript() to register your script...may resolve problem ...
Check this resolve your problem : Add JavaScript programmatically using RegisterStartupScript during an Asynchronous postback
I would recommend on a different approach. To create a dynamic javascript for any language. I would create a reference to a dynamic file. For this example I will use .NET
Create a test.aspx page and add this script:
<script type="text/javscript" src="js/foo.aspx"></script>
Make sure your page response with the right content type. So for this instance I would add this on page load code behind for your foo.aspx:
Response.ContentType = "application/javascript";
On the foo.aspx html view add your javascript code.
alert("<%=DateTime.Now%>");
Browse your test.aspx page and you should see an alert with the current date
You should be able to move forward from here. The goal is to separate the javascript file from the static page.
Happy Coding.
How to change text of ASP Button control on anchor tag click
We have an ASP Button below and we want to change text when WE click on anchor tag
<asp:Button ID="btn_Add" runat="server" CssClass="button2" onclick="btn_Add_Click"/>
We have following two anchor tags
Add New
Add New
Now we add following code in script tag
<script type="text/javascript" language="javascript">
function changeText1() {
document.getElementById("lbl_header").innerText = 'Add New Teacher';
document.getElementById("btn_Add").value = 'Add';
}
</script>
<script type="text/javascript" language="javascript">
function changeText2() {
document.getElementById("lbl_header").innerText = 'Delete Teacher';
document.getElementById("btn_Add").value = 'Delete';
}
</script>

Javascript event on page postback

Is there any javascript event which is triggered on postback?
If not, how can I run client side code immediately after or before a page postback?
I believe what you are looking for is the Sys.WebForms.PageRequestManager beginRequest Event
Excerpt:
The beginRequest event is raised before the processing of an
asynchronous postback starts and the postback is sent to the server.
You can use this event to call custom script to set a request header
or to start an animation that notifies the user that the postback is
being processed.
Code Sample: (From the link)
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args)
{
var elem = args.get_postBackElement();
ActivateAlertDiv('visible', 'AlertDiv', elem.value + ' processing...');
}
function EndRequestHandler(sender, args)
{
ActivateAlertDiv('hidden', 'AlertDiv', '');
}
function ActivateAlertDiv(visstring, elem, msg)
{
var adiv = $get(elem);
adiv.style.visibility = visstring;
adiv.innerHTML = msg;
}
</script>
I hope that helps. The PageRequestManager class seems to be little known about and little utilized.
Take a look at:
Run javascript function after Postback
I solved my problem using this:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function (s, e) {
alert('Postback!');
});
</script>
there are a lot of options too, like
$('#id').live('change', function (){});
$(document).ready(function () {});
ClientScriptManager.RegisterStartupScript(this.GetType(), "AKey", "MyFunction();", true);
and keep going. depends on what you need.
PageRequestManager events: https://learn.microsoft.com/en-us/previous-versions/aspnet/bb398976(v=vs.100)
You could add the javascript in your page load like this...
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert",
"alert('hello world');", true);
OR
Page.ClientScript.RegisterStartupScript(this.GetType(), "alertScript",
"function Hello() { alert('hello world'); }", true);
The Page.ClientScript object has a RegisterOnSubmitStatement This fires after any input submits the form. This may or may not be what you're looking for, but I've used it for notifying the user of unsaved changes in editable forms.
The advantage to using this over RegisterStartupScript is that with RegisterOnSubmitStatement, if a user navigates away and back using the browser, whatever script you've injected using RegisterStartupScript could possibly fire again, whereas RegisterOnSubmitStatement will only run if the user has submitted the form.
Use AJAX, with an event handler for the onComplete.
The onsubmit event on the form tag
When using jQuery it's like this
$("#yourformtagid").submit(function () {
...
}
There isn't a javascript event triggered when a page loads after a postback, but you can add javascript to your html template (.aspx file) and only run it if the page was posted, like this:
<script type='text/javascript'>
var isPostBack = '<%= this.IsPostBack%>' == 'True';
if (isPostBack) {
alert('It's a PostBack!');
}
</script>
If you want to customize the javascript to run only under particular conditions (not just any postback), you can create a page-level variable (protected or public) in your page's class and do something similar:
var userClickedSubmit = '<%= this.UserClickedSubmit%>' == 'True';
if (userClickedSubmit) {
// Do something in javascript
}
(Nothing against ClientScript.RegisterStartupScript, which is fine - sometimes you want to keep your javascript in the page template, sometimes you want to keep it in your page class.)

Categories

Resources