Server controls and building HTML - ASP.NET - asp.net

I render HTML returned from an ajax call and currently uses simple html controls and the string that is returned from the ajax call looks like this:
string s = "<tr><td>MyLink</td></tr>";
Now, on the click on these links I need to do some processing on the server side to determine where I need to navigate to and for other information. My understanding is that I cannot use <asp:linkbutton /> in this html string I am building.
How do I make a server side call if i don't want to use ajax.

You don't necessarily need to use ASP .NET server controls to enact server-side logic in a post-back. The link for which you manually build the HTML and return in the AJAX call can direct the user to an HttpHandler (or even an aspx page) and pass necessary values to that handler/page on the query string. Then that handler/page can perform its server-side logic and redirect as necessary.
Maybe I've misunderstood the problem? Is there a specific reason why you're looking to use a LinkButton in particular?

Write a javascript function and call it from each link's onlick like this:
My Link
someFunc can then set a hidden input field to the value you want the server to react to. This could be anything from the link element (the text of the link, the value of an attribute you specify in your AJAX response, etc.). At the end of the function, call form1.submit();
function someFunc(link){
var hiddenInput = document.getElementById("ClickedLink");
hiddenInput.value = link.innerText;
form1.submit();
}
Then on the server, in your On_Load in the code behind:
if(ClickedLink.Value != ""){
ProcessLinkClick(ClickedLink.Value);
}

Related

Query string in client side

I am a beginner in using ASP.NET and JavaScript. I've stumbled upon this problem:
In my page1.aspx, I use Response.Redirect("page1.aspx#download") using an anchor.
Now, I want to get the Request.QueryString upon loading on the client side using JavaScript.
Can someone help me with this?
page1.aspx#download
By the above declaration you will not be able to get this Download as a text on other page. You need to declare it like this
page1.aspx?Value=download
and on page1.aspx server side you need to get the value by calling
lblText.Text = Request.QueryString["Value"];
lblText will be asp:label on client side of this page and you can call it on page load so your value will be diplayed.

__doPostBack outside of href causes full page postback

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)

fadeIn/fadeOut div tag after executing some server side code

Here is my code
<div id="AuthenticateUser" runat="server" style="display:block" >
//login control
<asp:button id="ValidateUser" ... />
</div>
<div id="ForceToChangePassword" runat="server" style="display:none" >
//reset password control
</div>
On click of "ValidateUser" button, I do check whether user is valid or not. Based on some condition I do need hide "AuthenticateUser" div tag and show "ForceToChangePassword" div tag.
I really like the jQuery fadeIn/fadeOut effect. I can easily do that on client side. But how can I give that effect after executing server side code?
I tried to call javascript method from code behind that method has a fadeIn/fadeOut logic but it seems like that javaScript method is never been called.
If you have the AJAX extensions, put this in the button event handler. (C# example, easily converted to vb.net)
ScriptManager.RegisterClientScriptBlock(this, GetType(this), "fader", "$('#AuthenticateUser').fadeOut(); $('#ForceToChangePassword').fadeIn();");
This will send a client script after the postback has completed. Here is the documentation. This also requires a ScriptManager on the page. If you don't have the AJAX extensions you can probably use it from the Page's method itself.
The best way is to replace your asp:button (which I'm assuming is doing a postback) with an html button and some javascript to make an AJAX call (or JSON & REST call).
jQuery supports REST services really well with their .ajax method.
http://api.jquery.com/category/ajax/
WCF also supports JSON & REST services very nicely.
http://www.west-wind.com/weblog/posts/324917.aspx
It's a match made in heaven.
When the web service call completes, a javascript method (specified in the jquery .ajax call) will get called, and you can do the fade at that point.
If you make any ajax request then you must have to call the function which handling fadeIn/fadeOut logic, within the response callback function. you have to do something like
$.ajax({
url: "url-to-backend",
success: function(msg){
changeDiv();
}
});
function changeDiv()
{
//your code to handle fadeIn/fadeOut logic;
}
Thanks
You need to use an AJAX call for something like this. http://api.jquery.com/category/ajax/
Basically, the javascript will send your login request to your serverside code. The serverside will send the response back (you can decide what kind of response).
Then use that response to determine if you should be fading in or not.
$.post('login.aspx', {credentials (hopefully encrypted)}, callbackFunction(dataFromServer){
if(dataFromServer == loggedin)
fadein
else
don't
});

How to run a javascript function before postback of asp.net button?

I'm using Javascript to create a DIV element and open up a new page by using onclientclick. This works great. Now, I need to write to it from the server side and this element must be created before it is posted back.
How do I get the javascript to execute before the postback?
Currently, I have to press the button twice because the element doesn't exist to write too on the first click.
To be clear, I need this to execute before the "OnClick" of the button.
Update: It looks like the Javascript function is called before the postback but the element is not updated until I run the second postback. Hmm
Update: Unfortunately it is a bit more complicated then this.
I'm creating a div tag in javascript to open a new window. Inside the div tag, I'm using a databinding syntax <%=Preview%> so that I can get access to this element on the server side. From the server side, I'm injecting the code.
I'm thinking this may be a chicken-egg problem but not sure.
UPDATE!
It is not the Javascript not running first. It is the databinding mechanism which is reading the blank variable before I'm able to set it.
Hmm
you don't have to rely on server controls to perform postbacks in asp.net. you can gain finer control of your app by posting from javascript whenever you are ready..
the framework auto generates a function called __doPostback(.....) and eventually calls it every time it needs to do a postback.
so. instead of using server control button, you can have a regular <button onclick="foo()" />
than once you're done performing all that you need, just call the __doPostback function.
asp.net gives you a nifty way to access that function with
Page.GetPostbackClientEvent (i believe, but there are couple methods that support this methodology)
http://msdn.microsoft.com/en-us/library/system.web.ui.page.getpostbackclientevent.aspx
enter code hereWould this work for you?
Javascript
function stuffYouWantToDo(){
//do your stuff
//then submit the .NET form
document.forms[0].submit();
}
.NET code
<asp:button ID="Button1" onClientClick="return false;stuffYouWantToDo();"/>
This should ensure that the stuff you want to do is done, then the form will be submitted. The return false prevents the form from being submitted when you first click the button and relies on the call in the stuffYouWantToDo function to submit the form.
If you want to use jquery you could do the following:
$(document).ready(function() {
var execScript = $(".myButton").attr("href").replace("javascript:", "");
$(".myButton").attr("href", "#").click(function() {
// Add before click logic here
eval(execScript);
});
});
Couldn't you simply add a custom validator somewhere in your form?

Raising javascript event from an ASP.NET user control and handling in ASP.NET page

In an ASP.NET page I have a user control and I want to perform some action within it using javascript. When that action is complete I want to raise an event (again in javascript) to be picked up by the containing ASP.NET page (again in javascript).
The reason I want to do this is because I have more than one user control on the page and I need the action performed in one user control to instantiate an action in another user control without doing a postback.
Does anyone know how to do this?
Many thanks.
Hi and thanks for the response.
What I'm trying to do is create some form of encapsulation. So if the javascript code does something in one user control that user control shouldn't know of the impact else where. It would raise an event in javascript which can be picked up by asp.net page rendered javascript which can in turn call a javascript method in another user control if it needs to.
The idea here is also to eliminate any need for a postback.
Hope this expains it better.
I think the simple way to implement what you are describing, is to forget about JavaScript events, and just supply a "callback" function to the user-controls.
The way i would implement it, would be to expose a public property on the user control, which takes the name of this JavaScript "callback-function". The user-control is then responsible for calling this function after it has finished its client-side job.
So the page that uses the user-controls will have to implement this JavaScript "callback-function", and then supply the name in properties to the user controls.
Makes sense?
You can simply run the javascript you need from the rendered HTML of your user control.
Click Me
By the sounds of things you want to create some form of controller in JavaScript. When the page loads each of your controls register with the controller. Then an action in one of your controls runs a function on the controller, which does something with the controls registered with it.
Your JavaScript could be as simple as:
var oControls = new Array();
doSomething = function() {
for(var i=0;i<oControls.length;i++) {
var oControl = document.getElementById(oControls[i]);
oControl......
}
}
So you need to register your control by using ScriptManager in your user controls render method.
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "Startup", String.Format("oControls.push('{0}');", ClientID), True);

Resources