Access value set using javascript in code behind in Master Page - asp.net

Im executing javascript on a master page that is onClick event of a Menu item i set it to a hidden field and on Init of the Master page im not able to access this hidden field value.
Regards

State isn't available in your controls until the Load phase. Before that you have to check in Request.Form

This is the Code. In Master Page, I add the tag
<asp:HiddenField ID="hdnPath" runat="server" Value=""/>
Then I have a script tag which runs a function setScript() that is every time Master Page is loaded
<script type="text/javascript" language="javascript">
setScript();
// I Navigate through all the menu items, which is navigate
// through all the "a" tags and then all of the a tags onclick
// event i add a new function ,below is the code
<script type="text/javascript" language="javascript">
setScript();
function setScript() {
var objMenu=document.getElementById('<%=_menu.ClientID %>');
var objHyperLinks=objMenu.getElementsByTagName('a');
for(var i=0;i<objHyperLinks.length;i++) {
var pageLoc=objHyperLinks[i].href;
objHyperLinks.item(i).onclick=function (){
return setEvent(this);
};
}
}
function setEvent(Loc) {
var pageLoc=Loc+"";
var iframePath=document.location.href;
var targetPath=pageLoc;
document.getElementById('<%=hdnPath.ClientID %>').value=targetPath;
if(document.all) {
document.all.frameLoader.src=targetPath;
} else {
var frame=window.frames;
frame[0].location.href=targetPath;
}
return false;
}
I alert the value of hdnPath right after the targetPath is assigned and I get to see the assigned value.

Related

$Find returns null

I have the following JScript on a page
<script type="text/javascript">
function ProcessButtonDisable() {
var button = $find("<%=ProcessButton.ClientID %>");
button.disabled = true;
}
</script>
and later
<asp:Button ID="ProcessButton" Text="Process All" runat="server" OnClick="Process_Click" OnClientClick="ProcessButtonDisable()" />
when running the page and firing off the button i get
Microsoft JScript runtime error: Unable to set value of the property 'disabled': object is null or undefined
and the dynamic page has converted it to:
<script type="text/javascript">
function ProcessButtonDisable() {
var button = $find("ctl00_ctl00_BodyContentPlaceHolder_MainContentPlaceHolder_ProcessButton");
button.disabled = true;
}
</script>
<input type="submit" name="ctl00$ctl00$BodyContentPlaceHolder$MainContentPlaceHolder$ProcessButton" value="Process All" onclick="ProcessButtonDisable();" id="ctl00_ctl00_BodyContentPlaceHolder_MainContentPlaceHolder_ProcessButton" />
as the control is clearly defined and the client id seems to be returning the correct id i don't know whats wrong
Any help?
ps in case this is not clear from the code the purpose of this is to prevent he user from clicking on the and resending the request before the page has time to reload after the initial click
-1 to all the previous answers for assuming JQuery. $find is a function defined by the Microsoft AJAX Library. It "provides a shortcut to the findComponent method of the Sys.Application class" which gets "a reference to a Component object that has been registered with the application through the addComponent method". Try using $get() instead, which "Provides a shortcut to the getElementById method of the Sys.UI.DomElement class."
This page explores both functions in detail: The Ever-Useful $get and $find ASP.NET AJAX Shortcut Functions
$find is differ from $.find. The first one is provides a shortcut to the findComponent method of the Sys.Application class which defined by the Microsoft AJAX Library. while the second is API method from jQuery which get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
So, $find has to find Component not html DOM. and ajax Library has to be defined.
For more information:
http://msdn.microsoft.com/en-us/library/vstudio/bb397441(v=vs.100).aspx
http://api.jquery.com/find/
try this:
<script type="text/javascript">
function ProcessButtonDisable() {
var button = $("#<%=ProcessButton.ClientID %>");
button.disabled = true;
}
</script>
[edit] or
<script type="text/javascript">
function ProcessButtonDisable() {
$("#<%=ProcessButton.ClientID %>").attr("disabled", "disabled");
}
</script>
You have to select what you are "finding" in first. For example, if you select document then use the method "find" you should have the result you want.
<script type="text/javascript">
function ProcessButtonDisable() {
var button = $(document).find(("<%=ProcessButton.ClientID %>");
button.disabled = true;
}
</script>
disabled is not a jQuery object property it is a DOM element property.
Try using either:
$('selector').get(0).disabled = true
, or
$('selector').attr('disabled','disabled');
You need to use the dot notation, as find() is a jQuery function, like this:
<script type="text/javascript">
function ProcessButtonDisable() {
var button = $.find("<%=ProcessButton.ClientID %>");
button.disabled = true;
}
</script>
Also, if you are going to take the trouble to look up the DOM element in your jQuery logic, then do not bother wiring up the OnClientClick on the server control; either wire up the click event via jQuery or pass the element itself to the JavaScript function:
Using jQuery to wire up the click event (recommended):
<script type="text/javascript">
$(document).ready(function() {
$("#<%=ProcessButton.ClientID%>").click(function() {
$(this).disabled = true;
});
});
</script>
Using the OnClientClick attribute to wire up the click event and pass the element (not recommended):
<asp:Button ID="ProcessButton" Text="Process All" runat="server" OnClick="Process_Click"
OnClientClick="ProcessButtonDisable(this)" />
<script type="text/javascript">
function ProcessButtonDisable(elem) {
elem.disabled = true;
}
</script>

Rebind Radgrid does not refresh when radwindow closes

I am trying to rebind my grid once a radwindow has been closed through master page. My grid is in a usercontrol in aspx page. In master page i have :
function CancelEdit() {
GetRadWindow().Close();
}
function CloseAndRebind() {
GetRadWindow().BrowserWindow.refreshGrid(); // Call the function in parent page
GetRadWindow().close(); // Close the window
}
function refreshGrid() {
$find("<%= RadAjaxManager1.ClientID %>").ajaxRequest("Rebind");
}
and I have the following javascript in the user conrtrol:
<script type="text/javascript" language="javascript">
function refreshGrid() {
$find("<%= RadAjaxManager.GetCurrent(me.Page).ClientID %>").ajaxRequest("Rebind");
}
</script>
Once I close update the database in radwindow i register a javascript:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "mykey", "CloseAndRebind();", True)
I can see my data source changing but the grid doesn't get updated. any suggestions?
EDIT ::
The structure is something like this:
I have master page which has the RadAjaxManager.
There is a main page which has a user control
Another user control inside above user control which has the RadGrid
Then there is an aspx page that opens as radwindow
Use the client-side API to rebind your grid, should be the correct way to do that:
In your child page:
function refreshGrid() {
$find("<%= YourGrid.ClientID %>").get_masterTableView().rebind();
}
To call a javascript function from the parent page, simply use this:
function CloseAndRebind() {
GetRadWindow().get_contentFrame().contentWindow.refreshGrid(); // Call the function in parent page
GetRadWindow().close(); // Close the window
}

Persist browser scroll position

I'm looking for a simple, efficient way to get the position of the browser vertical scrollbar and save it into a session variable in an ASP page.
What I'm trying to do is when the user changes a page I've the scroll position stored in a session variable so that when the user returns to the page the page will scroll to their last position.
Is there a way to do this? I've seen examples of persisting the scroll position on postback but nothing yet doing exactly what I'm trying to do :(
If anyone can point me in the right direction id be grateful.
EDIT:
Ok so based on the example below I noticed that when the user clicks a row in my gridview they navigate to the next page but my event handler never gets fired.
This leads me to suspect that the scroll position wasn't being saved, I'm guessing the form isn't being submitted)
My event handler looks like :
Protected Sub save(ByVal sender As Object, ByVal e As EventArgs) Handles ScrollPosition.ValueChanged
Session.Add("ScrollPosition", ScrollPosition.Value)
End Sub
I figured it was easiest to use the valueChanged event to grab the value and put it into the session
Next my Script.... I'm trying to do it based on my very limited knowledge of Jquery!
<script type="text/javascript">
$(function () {
//Retrieve and use the existing scroll position from the hidden field
var scrollPosition = $('#<%= ScrollPosition.ClientID %>').val();
$(window).scrollTop(scrollPosition);
/*
//Handle the main forms submit event and store the scroll position
$('#<%= form1.ClientID %>').submit(function () {
var currentScrollPosition = $(window).scrollTop();
$('#<%= ScrollPosition.ClientID %>').val(currentScrollPosition);
});
*/
});
$(document).ready(function () {
$("#gvTickets").click(function () {
var currentScrollPosition = $(window).scrollTop();
$('#<%= ScrollPosition.ClientID %>').val(currentScrollPosition);
})
});
</script>
The idea behind the script is that when a row in gvTickets is clicked the scroll position will be stored which should trigger my value changed event handler
I'm not getting any errors but neither am I getting the desired behaviour :(
Also in my page load I have :
If Not IsPostBack Then
If (Session("ScrollPosition") = Nothing) Then
ScrollPosition.Value = 0
Session("ScrollPosition") = 0
Else
ScrollPosition.Value = Session("ScrollPosition")
End If
Try storing the scroll position on submit of the form in a HiddenField control.
The HiddenField control will then be available in your code behind, so you can store the value as required.
You can then use the value from the HiddenField control to set the scroll position when the page loads.
See an example below (uses JQuery):
Markup
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<!-- Set the path to JQuery here -->
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
//Add some line breaks
for (i = 0; i < 1000; i++) {
$('body').prepend('<br/>');
}
//Retrieve and use the existing scroll position from the hidden field
var scrollPosition = $('#<%= ScrollPosition.ClientID %>').val();
$(window).scrollTop(scrollPosition);
//Handle the main forms submit event and store the scroll position
$('#<%= form1.ClientID %>').submit(function () {
var currentScrollPosition = $(window).scrollTop();
$('#<%= ScrollPosition.ClientID %>').val(currentScrollPosition);
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div style="position:fixed;top:0px;left:0px;">
<asp:HiddenField ID="ScrollPosition" runat="server" Value="0" />
<asp:Button ID="Button1" runat="server" Text="Post Back" OnClick="Button1_Click" />
<asp:Label ID="CurrentScrollPosition" runat="server"></asp:Label>
</div>
</div>
</form>
</body>
</html>
Code Behind
protected void Button1_Click(object sender, EventArgs e)
{
CurrentScrollPosition.Text = string.Format("Scroll position: {0}", ScrollPosition.Value);
}
Edit (Based on comments)
Try handling the window scroll event, updating the hidden field whenever the scroll position changes:
<script type="text/javascript">
$(function () {
$(window).scroll(function () {
var currentScrollPosition = $(window).scrollTop();
$('#<%= ScrollPosition.ClientID %>').val(currentScrollPosition);
});
});
</script>
Edit
For me, the following code sets the scroll position hidden field to 0 on load. Then on subsequent post backs stores the value in the hidden field in the "ScrollPosition" session variable.
I am then able to print the scroll position out to the screen. See below:
The control firing the postback in my example is a Button, however any control could initiate the postback and it will still function in the same manner.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Default to 0
ScrollPosition.Value = "0";
//If ScrollPosition session variable is null, store the default
//Else set the scroll position to the value stored in session.
if (Session["ScrollPosition"] == null)
{
Session.Add("ScrollPosition", ScrollPosition.Value);
}
else
{
ScrollPosition.Value = Session["ScrollPosition"].ToString();
}
}
else
{
//On subsequent postbacks store the new scroll position
Session.Add("ScrollPosition", ScrollPosition.Value);
}
OutputScrollPosition();
}
private void OutputScrollPosition()
{
CurrentScrollPosition.Text = string.Format("Scroll position: {0}", Session["ScrollPosition"]);
}
Hope this helps.

How to capture 'Update' click event in ASP.NET GridView with jQuery

I need to capture the 'Update' click event with jQuery in an asp.net GridView and have no way of knowing where to start. I'm still rather new to jQuery. My GridView is attached to a SQLDataSource and, naturally, has all the bells and whistles that that combination affords. Any help would be greatly appreciated.
Simply add the script block anywhere after the GridView is declared and it should work with the default non-templated GridView column. No code in the codebehind as it is purely a Javascript solution.
Use this if you are using a Link-type GridView column:
<script type="text/javascript">
// a:contains(The text of the link here)
$('#<%= theGridViewID.ClientID %> a:contains(Update)').click(function () {
alert('Update click event captured from the link!');
// return false: stop the postback from happening
// return true or don't return anything: continue with the postback
});
</script>
Use this if you are using a Button-type GridView column and you don't want your Javascript to block the postback:
<script type="text/javascript">
// :button[value=The text of the button here]
$('#<%= theGridViewID.ClientID %> :button[value=Update]').click(function () {
alert('Update click event captured from the button!');
});
</script>
Use this if you are using a Button-type GridView column and you want to have control whether to continue with the postback or not:
<script type="text/javascript">
// :button[value=The text of the button here]
var updateButtons = $('#<%= theGridViewID.ClientID %> :button[value=Update]');
updateButtons
.attr('onclick', null)
.click(function () {
alert('Update click event captured from the button!');
var doPostBack = true; // decide whether to do postback or not
if (doPostBack) {
var index = updateButtons.index($(this));
// 'Update$' refers to the GridView command name + dollar sign
__doPostBack('<%= theGridViewID.UniqueID %>', 'Update$' + index);
}
});
</script>
Update: I think this would be a better solution in replacement of the last (3rd) script block I presented above, since you won't need to update the __doPostBack function call manually based on the command name, and as such, it should be less error-prone:
<script type="text/javascript">
// :button[value=The text of the button here]
var updateButtons = $('#<%= theGridViewID.ClientID %> :button[value=Update]');
updateButtons.each(function () {
var onclick = $(this).attr('onclick');
$(this).attr('onclick', null).click(function () {
alert('Update click event captured from the button!');
var doPostBack = true; // decide whether to do postback or not
if (doPostBack) {
onclick();
}
});
});
</script>
Credit to Aristos for this idea. :)
Ok here is my solution to capture only one update (or more) from a button.
This is the javascript code that I run on update click
<script type="text/javascript">
function NowRunTheUpdate(){
alert("ok I capture you");
}
</script>
and here is the page code
`<asp:GridView ID="MyGridView" runat="server" OnRowDataBound="MyGridView_RowDataBound" ... >`
<asp:ButtonField Text="update" CommandName="Update" ButtonType="Button" />
...
Here is the code thats run behind and set the javascript.
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// I go to get the button if exist
Button button = control as Button;
if (button != null && button.CommandName == "Update")
// Add delete confirmation
button.OnClientClick = "NowRunTheUpdate();";
}
}
}
}
You need to attach a client-side event listener to the click event of the Update [link]button. I don't think it can be done using AutoGenerateEditButton="true" if you are doing it that way. You'll need to use a TemplateField so that you can manipulate the button. Then you can use jQuery to bind to the click event of the button.
Add the update column to the column templates. Convert it to a custom column, and modify it in such a way you can hook to it with jquery i.e. like adding a css class to it.
Gridview is nothing but a table with a bunch of "tr" and "td". If you understand that concept then it would be easy for you to handle anything at client side. If you have enabled auto everything then it will be a link which would result for Edit, Delete, Update or Cancel (Check View Source). The code given below should capture the update click event:
$("a:contains(Update)").live("click", function() {
//alert("hi"); do what needs to be done
return false;//would not sent the control back to server
});
HTH

LinkButton does not invoke on click()

Why doesn't this work?
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.myButton').click();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LinkButton id="ttt" runat="server" PostBackUrl="~/Default.aspx" CssClass="myButton">Click</asp:LinkButton>
</div>
</form>
Do you want to submit the form, or add a Click event?
Your link button translates to
<a id="ttt" class="myButton" href="javascript:WebForm_DoPos[...]">Click</a>
, so it has no on-click javascript. Therefore, .click(); does nothing.
I haven't test it, but maybe this will work:
eval($('.myButton').attr('href'));
trigger('click') fires jQuery's click event listener which .NET isn't hooked up to. You can just fire the javascript click event which will go to (or run in this case) what is in the href attribute:
$('.myButton')[0].click();
or
($('.myButton').length ? $('.myButton') : $('<a/>'))[0].click();
If your not sure that the button is going to be present on the page.
Joe
If you need the linkbutton's OnClick server-side event to fire, you need to use __doPostback(eventTarget, eventArgument).
ex:
<asp:LinkButton ID="btnMyButton" runat="Server" OnClick="Button_Click" />
<script type="text/javascript">
function onMyClientClick(){
//do some client side stuff
//'click' the link button, form will post, Button_Click will fire on back-end
//that's two underscores
__doPostBack('<%=btnMyButton.UniqueID%>', ''); //the second parameter is required and superfluous, just use blank
}
</script>
you need to assign an event handler to fire for when the click event is raised
$(document).ready(function() {
$('.myButton', '#form1')
.click(function() {
/*
Your code to run when Click event is raised.
In this case, something like window.location = "http://..."
This can be an anonymous or named function
*/
return false; // This is required as you have set a PostbackUrl
// on the LinkButton which will post the form
// to the specified URL
});
});
I have tested the above with ASP.NET 3.5 and it works as expected.
There is also the OnClientClick attribute on the Linkbutton, which specifies client side script to run when the click event is raised.
Can I ask what you are trying to achieve?
The click event handler has to actually perform an action. Try this:
$(function () {
$('.myButton').click(function () { alert('Hello!'); });
});
you need to give the linkButton a CssClass="myButton" then use this in the top
$(document).ready(function() {
$('.myButton').click(function(){
alert("hello thar");
});
});
That's a tough one. As I understand it, you want to mimic the behavior of clicking the button in javascript code. The problem is that ASP.NET adds some fancy javascript code to the onclick handler.
When manually firing an event in jQuery, only the event code added by jQuery will be executed, not the javascript in the onclick attribute or the href attribute. So the idea is to create a new event handler that will execute the original javascript defined in attributes.
What I'm going to propose hasn't been tested, but I'll give it a shot:
$(document).ready(function() {
// redefine the event
$(".myButton").click(function() {
var href = $(this).attr("href");
if (href.substr(0,10) == "javascript:") {
new Function(href.substr(10)).call(this);
// this will make sure that "this" is
// correctly set when evaluating the javascript
// code
} else {
window.location = href;
}
return false;
});
// this will fire the click:
$(".myButton").click();
});
Just to clarify, only FireFox suffers from this issue. See http://www.devtoolshed.com/content/fix-firefox-click-event-issue. In FireFox, anchor (a) tags have no click() function to allow JavaScript code to directly simulate click events on them. They do allow you to map the click event of the anchor tag, just not to simulate it with the click() function.
Fortunately, ASP.NET puts the JavaScript postback code into the href attribute, where you can get it and run eval on it. (Or just call window.location.href = document.GetElementById('LinkButton1').href;).
Alternatively, you could just call __doPostBack('LinkButton1'); note that 'LinkButton1' should be replaced by the ClientID/UniqueID of the LinkButton to handle naming containers, e.g. UserControls, MasterPages, etc.
Jordan Rieger

Resources