__doPostBack outside of href causes full page postback - asp.net

I have a custom control (ascx) which implements the IPostBackEventHandler interface for intercepting custom events triggered by custom rendered HTML links.
In this control I use an update panel and inside the update panel I use a literal control in which I render custom HTML links.
When I render the HTML links inside the literal control I use a StringBuilder with the following code:
sb.AppendFormat ("Text",
this.Page.ClientScript.GetPostBackClientHyperlink(this, custom_string_param));
Hyperlinks are rendered fine, and when clicking on them an asynchronous postback is triggered and a partial update is fired (since all links are rendered inside the Update panel).
The problem is that I need to do some custom Javascript before firing the __doPostBack which is rendered with the above code. So here is a simplified version of the changed code:
sb.AppendFormat ("Text",
custom_string_param);
Also in the ascx markup I use the following code (inside or outside the Update panel):
<script language="javascript" type="text/javascript">
function JSFunc(param) {
// custom js code here ....
__doPostBack('<%=this.ClientID%>', param);
}
</script>
The problem here is that when a link is clicked it performs a full postback and not a partial one. I also tested more simple versions of the above code and it seems that if you remove the __doPostBack from the href or the onclick events from the link ( tag) and move it to a custom js function which in turns you supply to the link, a full postback is triggered.
Note that there is no error on the page and in both cases the code work correctly. The page is rendering correctly depending on the parameters returned from the __doPostBack, but in the second case a full instead of partial postback is firing.
Any ideas?
Thanks in advance,
George

I think you can't call __doPostBack with the ClientID. It actually uses UniqueIDWithDollars, but generally with ASP.NET Web Forms I say: you don't want to know.
Since calling this method is all about abstracting away the details of how post back works, you would be better off asking the framework for the code. Luckily, there's a special method just for that, which will take care of the details. In your code it would look like something like this:
<script language="javascript" type="text/javascript">
function JSFunc(param) {
// custom js code here ....
<%= Page.ClientScript.GetPostBackEventReference(this, custom_string_param) %>
}
</script>
This let's the client script manager create the piece of JavaScript code, using a reference to your user control (this) and any custom event argument (custom_string_param).
There's one caveat though. When calling it this way, it will add javascript: to the beginning of the string.
To override this behaviour, you need to use an overload of GetPostBackEventReference that accepts an instance of PostBackOptions as its first argument, the instance having its RequiresJavaScriptProtocol property set to false.
PostBackOptions options = new PostBackOptions(this, custom_string_param)
options.RequiresJavaScriptProtocol = false;
Page.ClientScript.GetPostBackEventReference(options)

Related

Register JavaScript alert at extreme end using RegisterStartupScript

(Note: Just to clarify the problem is not specifically related to C1WebDateEdit. It could be with any custom control which require JavaScript to render actual control)
I have many C1WebDateEdit controls in my page. On a button click based on some condition I am displaying JavaScript alert message ScriptManager.RegisterStartupScript. These controls are inside UpdatePanel. The issue I am facing with it is, when these C1WebDateEdit has not value and page displays alert message, it displays "01/01/0001" behind the alert box and on closing alert it shows empty textboxes.
The reason is, C1WebDateEdit creates actual control using JavaScript. and page renders alert message JavaScript before C1WebDateEdit controls' JavaScript.
For example:
HTML markup
alert JavaScript
C1WebDateEdit JavaScript
Logical solution is get alert JavaScript after C1WebDateEdit JavaScript because it will allow C1WebDateEdit to load fully before alert box.
I found no inbuilt way in asp.net to change sequence, so I tries solution given here but It didn't work for me.
One possible solution I am thinking that I create Custom or WebUserControl and place at it last at the page in the UpdatePanel and PreRender event I call ScriptManager.RegisterStartupScript to register alert message. Logically I think it will work but trying to find that any one implemented any other solution for it?.
Other possible solution is use "pageLoaded" event of PageRequestManager. I created below function for temporary fix:
function delayedAlertBox(strMsg)
{
var fnc = function (a, b)
{
//remove reference so on next call it do not show previous alerts.
Sys.WebForms.PageRequestManager.getInstance().remove_pageLoaded(fnc);
alert(strMsg);
}
//add function reference to call on Ajax pageloaded event
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(fnc);
}
and calling in asp.net like simple function as given below:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "dd", "delayedAlertBox('Hi, how are you?')", True)
But still looking for any other good alternative. If I found other, I will post it.

Why javascript function not working from content page onload?

I am using ASP.NET 3.5.
I have a content page and I want to call a javascript function on this page's load event.
I tried adding:
onload="GetLocalDate();"
within the content page placeholder tag, but it is not working. But when I call this function from any button's OnClientClick event, it works.
How to make it work on Content Page's load event?
The content page "Placeholder" tag is a server side only control. It doesn't produce any code on the client other than arranging its contents etc. As such, the JavaScript onload handle is never rendered.
Examine your browser / client-side source to verify this.
Have you tried calling from document.ready?
$(document).ready(function () {
GetLocalDate();
}
Put that inside script tag on your page
<script type="text/javascript">
function pageLoad(){
GetLocalDate();
}
</script>
$(document).ready(function () {
GetLocalDate();
}
Should work. Since it was not working for you, I would assume that you do not have a reference to the jQuery library in your page.
If you don't want to include the jQuery library in your project for some reason, you could inject it from server-side code within your content page:
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(...) <-- add necessary details here (the Type, scriptname, the text, and a Boolean to whether you need it to include its own tags)
You should also check to make sure it hasn't already been registered before using it though (IsStartupScriptRegistered).

Is there a global "onRequestComplete" event when using ASP.Net Update Panels?

I have a master page with a public ShowWaitingDialog property. When set to true, I simply show a modal "Please wait..." overlay when the form is submitted. This is done by registering a client-side function called ShowWaitingDialog() using the following:
Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "ShowWaitingDialog", "ShowWaitingDialog()");
As a side note, I also have a function the coder can use if linking to a page that may take a while to load:
public void AttachWaitingDialog(HyperLink HyperLinkControl){
if (this.ShowWaitingDialog)
HyperLinkControl.Attributes.Add("onclick", "ShowWaitingDialog();");}
These work just fine until an UpdatePanel is introduced onto the page. The dialog is correctly shown when a postback happens inside an update panel. However, it never goes away when the request is complete. I was hoping there was some sort of global complete event that the Microsoft ajax framework uses when making update panels requests. That way I could close my modal overflow when executed. Is there?
I haven't tried it yet, but I guess I could use the ScriptManager to always register a startup script which hides the modal overlay, but I was wondering if there was another way.
You can use Javascript and use the PageRequestManager clientside api provided by Microsoft Ajax framework.
<script type='text/javascript'>
var pageMgr = Sys.WebForms.PageRequestManager.getInstance();
pageMgr.add_beginRequest(BeforeAjaxRequest);
pageMgr.add_endRequest(AfterAjaxRequest);
function BeforeAjaxRequest(sender, args)
{
alert('MyReqeustStart');
}
function AfterAjaxRequest(sender, args)
{
alert('MyReqeustEnd');
}
</script>
More Details here:
http://msdn.microsoft.com/en-us/library/bb311028.aspx
I'm not sure with UpdatePanels, but you might take a look at the Application_EndRequest method in Global.asax

Using Javascript to detect when a user has selected an item in an ASP.NET listbox

I am developing an ASP.NET web application that incorporates google maps. I have an ASP.NET listbox on my page which contains a list of items. When the user selects one of the items, I'd like to show this item on the map. The main complication lies in the fact that google maps uses javascript to control it and the listbox is a server control.
I can think of two ways to do this. The first would involve the listbox calling a javascript function when the user selects a new item. I can then write this function to perform the necessary map operations. Unfortunately, the OnSelectedIndexChanged property of the listbox doesn't seem to support javascript functions.
The second involves wrapping an UpdatePanel around the listbox and getting the listbox to perform a postback. In the SelectedIndexChanged event in VB/C#, I would the need to somehow make a call to a javascript function which would then update the map.
Which solution can I use?
Thanks
--Amr
In your codebehind (in your pageload) just add a javascript handler to the OnChange attribute that points to your javascript function. Eg:
lbYourListBox.Attributes.Add("onChange", "UpdateYourMap();");
You could also add this to your control using inline javascript as well but I prefer to do it in the codebehind so that the framework can handle matching up the names.
You could simply embed javascript into your page, avoidig relying on ASP with it. Put the code into your document body:
<script language="javascript">
body.onload=function(){
var lb=document.getElementById("yourlistboxid");
lb.onChange = function(){
// put your handling code here
}
}
</script>
to demo the other approach, here's a rough guide:
void listbox_SelectedIndexChanged( ... ) {
string js = string.Format("callToMapsFunction({0});", listbox.SelectedValue);
string scriptKey = "mapscript";
ScriptManager.RegisterStartupScript( listbox, typeof(ListBox), scriptKey
, js, true);
}
RegisterStartupScript runs whatever javascript you give it after the partial postback completes. you don't necessarily have to pass the listbox value- just whatever data you want to provide to the maps api. the first 3 items are for preventing the script from registering a bunch of times (as far as I know). the true at the end tells the scriptmanager to automagically add opening and closing tags around your js code.

How to call javascript function from c#

I like to call a JavaScript function from c#. Can any one can give me code snippet.
More detail...
I have a asp.net page which has a asp button. when i click that button, i like to call javascript function.
like wise....
in my asp.net page,
<button id="save" onclick="i like to call a method resides in asp.net page'>Save</button>
More and more details...
when click the asp.net button, i like to perform some server side action and then like to call a javascript function from there itself...
For an asp:button you use OnClientClick
<asp:Button id="myid" runat="server" OnClientClick="alert('test')" />
On the assumption that you're coding in ASP.NET (including MVC), calling a JavaScript function would mean embedding the call in JavaScript into your ASPX code, like so:
<script type="text/javascript">
doSomething();
</script>
You do have the opportunity to pass information from your C# to the JS call, just as you would have any other code alter the results of your ASPX:
<script type="text/javascript">
doSomething("<%= GetSomeTextFromCSharp(); %>");
</script>
This is really stretching the definition of "calling JavaScript from C#" though. What you're doing is having your C#/ASPX code generate HTML/JavaScript, which the browser then interprets as it would any other HTML/JS (regardless of how it was generated).
Perhaps you could explain what you're trying to do a bit more.
i tried with this code it works for me check whether it helps
1)
Page.ClientScript.RegisterStartupScript(this.GetType(), "click", "alert('Informations');", true);
The other way is call the javascript method which is written in source page
Page.ClientScript.RegisterStartupScript(this.GetType(), "click", "xyz();", true);
You can't "call" a Javascript function from ASP.NET C# code-behind. You can write additional Javascript to the webpage. By the time the page is sent back to the user and the Javascript exists, your code-behind is gone. You can write out to a Literal or do a Response.Write()
Response.Write("<script language='javascript'>alert('Hellow World');</script>");
Sarathi, based on your recent update, it's not clear that you need any C# interaction at all. Your <button> appears to be strictly client-side (ie: HTML) with no ASP.NET interaction within it. To call your JavaScript function you'd attach the function call to the onclick attribute of the button tag:
<button id="save" onclick="mySaveFunction();'>Save</button>
Note that mySaveFunction() just needs to be defined in the browser's load stack for the current page. That means it could be defined in any of:
The ASPX page that holds the <button>
The Master page for the current ASPX page
One of the User controls (or MVC partials) loaded by the current ASPX page
An external JavaScript file that's loaded by one of the above.
Lastly, I'd just like to reiterate that there's nothing particularly C#/ASP.NET-specific about this. You could do the same with any language/framework, including static HTML files. Your question appears to be entirely JavaScript-dependent.
For the window object:
http://msdn.microsoft.com/en-us/library/ms536420%28VS.85%29.aspx
window.execScript
For the page pbject:
http://msdn.microsoft.com/en-us/library/dfbt9et1%28v=VS.71%29.aspx
RegisterClientScriptBlock
RegisterOnSubmitStatement
RegisterStartupScript
etc ...
you can call javascript function from code behind page ..for example you have closewindow function definition part in javasript..if you want to execute that function,you can write following codings in any click event in code behind page..
ClientScript.RegisterClientScriptBlock(GetType(), "close", "<script language=javascript>Closewindow();</script>", false);

Resources