.toggle() a div with asp:button - c#

I have a basic div that I want to .toggle() OnClientClick of an asp:button. It works as far as the code goes but I think that the OnClick event handler on the server side is causing the div to reset after it is clicked. Basically what happens is the div disappears for about .01ms and then reappears right away. Here is the simplest code example of my problem.
Here is an example of what happens:
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Testing</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function ToggleMe() {
$('#toggleMe').toggle();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="toggleMe">
<label>Hello World</label>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" OnClientClick="ToggleMe();"/>
</form>
</body>
</html>
Default.aspx.cs
using System;
namespace WebApplication2
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
int i = 5;
}
}
}
I have tried .removeClass, .addClass, .css... I don't think it's as much an issue with the jQuery that I am using as it is with the postback that happens on the button click.
I am running Chrome to test this if that matters.
Thanks in advance for your time and help!

The javascript part of your HTML executes in the user's browser. The protected void button1_click method executes on the server. What is happening is that the user's browser will toggle the div correctly, causing it to disappear. Unfortunately, the HTML of the ASP.NET button will then resubmit the page, meaning the browser refreshes the HTML from your server. The server has no concept of the toggle happening because the javascript did not execute there, and while int i is set to 5, the div gets re-set to being visible after the page refreshes after going to your server. Your options are:
1) don't use any server side logic for the button click, and get rid of
<asp:Button ID="Button1" ... />
and replace it with
<input type="button" onclick="ToggleMe();">your text</input>
and handle all of your client side logic in your javascript. If you need to set int i = 5 on the server, use JQuery.Ajax to talk back to the server.
2) use only server side .NET to do this. This is implemented like so:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Testing</title>
</head>
<body>
<form id="form1" runat="server">
<div id="toggleMe" runat="server">
<label>Hello World</label>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
</html>
And
protected void Button1_Click(object sender, EventArgs e)
{
int i = 5;
toggleMe.Visible = !toggleMe.Visible;
}

when u click the aspx:Button, it submits the page. it is much easier if you use regular html button
<input type="button" onclick="ToggleMe()">Button</input>
and please add a "return false;" statement to your code below
function ToggleMe() {
$('#toggleMe').toggle();
return false;
}

Related

Postback fires before validation when using CustomValidator

I have made a simple project to explain my problem.
This is my Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:CustomValidator ID="cusDate"
runat="server"
ValidateEmptyText="true"
OnServerValidate="DateValidate"
ValidationGroup="DateVal"
ControlToValidate="txtDate"
ErrorMessage="Date error"></asp:CustomValidator>
<asp:ImageButton ID="btnSaveDate"
CausesValidation="true"
ValidationGroup="DateVal"
ImageUrl="~/Images/save_32.png"
runat="server" />
</div>
</form>
</body>
</html>
And this is my Default.aspx.cs
using System;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) <<<<<<BREAKPOINT 1 HERE
{
}
}
protected void DateValidate(Object source, ServerValidateEventArgs args)
{
args.IsValid = false; <<<<<<BREAKPOINT 2 HERE
}
}
}
I set two breakpoints, as shown above, and run the application. When I click "btnSaveDate" it first stops at breakpoint 1 and then at breakpoint 2. I thought it would stop at breakpoint 2 first, then reload the page and then stop at breakpoint 1.
Is there something wrong in the code or should it behave like this?
I have read many articles about this and tried a lot of different solutions, but no one has worked so far.
According to the ASP.NET Page Life Cycle, the Postback event handling happens after the Load event.
If the request is a postback, control event handlers are called. After
that, the Validate method of all validator controls is called, which
sets the IsValid property of individual validator controls and of the
page. (There is an exception to this sequence: the handler for the
event that caused validation is called after validation.)
A postback means that a client is making an http request to the server and, every time a request arrives to the server, the Page Life Cycle stages are executed in this exact order. So the second answer is no, is not possible to enter in the breakpoint 2 then before entering the breakpoint 1.

Adding OnClick event to ASP.NET control

i would like to create OnClick event for my panel. So far now the most of the google results look more or less like this: adding onclick event to aspnet label. Is there any way, to call codebehind function from javascript or panel attributes? Because I would like to Redirect user to a new page and before that save some information in ViewSTate or Sessionstate. Any suggestions?
In your java script method raise a __dopostback call to a Server side method.
<script type="text/javascript">
function YourFunction()
{
__doPostBack('btnTemp', '')
}
</script>
Where btnTemp is a server side button, so write a onClick event of this button on server side, where you can do the processing and then redirect to other page.
You can have a good understanding of dopostback at DoPostBack Understanding
My aspx page is like:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script type="text/javascript">
function CallMe() { __doPostBack('btnTemp', '') }
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="btnTemp" runat="server" Text="Test" onclick="btnTemp_Click" />
<div> <asp:Label ID="Label1" runat="server" Text="Label1"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></div>
</form>
</body>
And my Server Side code is as:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Attributes.Add("onClick", "CallMe();");
}
protected void btnTemp_Click(object sender, EventArgs e)
{
}
Thats the code that I have written, I haven;t included the using statement, Page directive etc in above code.
There is a PostBackUrl property on a ASP.NET Button, you could render the button as normal then postback to a different page - this is where your OnClick method would need to be declared.
I would strongly recommend against posting back to the same page then doing a Response.Redirect(), consider the traffic. The browser requests the page, posts back then is sent a HttpRedirect and then navigates to the new page. With the method I have outlined above this is not required and the browser has to make one request less (meaning the message doesn't have to be sent or the page rebuilt on the server) and is a significant performance benefit.

How can I clear label text after some amount of time from code behind in asp.net?

I am assigning some text to Label after button click as follows:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Hello";
}
After some amount of time, say 30seconds, I would like to clear the Label text.
Can any one help me?
I tried the following script, but it doesn't work for me.
$(document).ready(function() {
$('#Label1').fadeOut(3000, function() {
$(this).html(""); //reset the label after fadeout
});
});
My design
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
$(document).ready(function() {
$('#<%= myLabel.ClientID %>').fadeOut(3000, function() {
$(this).html(""); //reset the label after fadeout
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label id="myLabel" runat="server"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>
</body>
</html>
If this is Asp.Net WebApplication I think you should use
$(document).ready(function() {
$('#<%= Label1.ClientID %>').fadeOut(3000, function() {
$(this).html(""); //reset the label after fadeout
});
});
In order to run some code after specified time you need to wrap the code in ready handler in
setTimeout(code, timeInMsAfterWitchToRunCode)
call. What you are doing is fading out immediately over a 3 seconds time. 3000ms that you are passing is parameter to fadeOut function telling it how long fading out should take.
Here you have working example:
http://jsfiddle.net/VPrEZ/3/
Note that in case of ASP.NET app you should use:
$('#<%= Label1.ClientID %>')
to select label. That is because you don't know the id of the control until runtime when control has runat="server" attribute set.
Be warned, that if you don't clear label's text on next postback you will got the same message again with each and every following postback. In my opinion it's better to show label text with client-side code rather to clear it. Or you may just clear label text each time in Page_Load.

Using Jquery not able to get correct out put

I did a small style changing app using Jquery in Asp.Net 3.5 .I am having IE7.
When i click on button the paragraph color should change.
Problem is ,the color is changing,it is not stable.Means just like blinking.
Please find the code below
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" src="scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#Button1").click(function() {
$("p").css("background-color", "Yellow")
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" />
<p>This Should be in <br/>
yellow</p>
</div>
</form>
</body>
</html>
Its because ASP.NET changes the ID attribute to be something it can resolve.
If you are using ASP.NET 4, set the ClientIDMode to AutoID.
If you are using anything else, change your selector to use "#<%= Button1.ClientID %>"
Also, return false to prevent the form from being postbacked.
try this :
$("#<%=Button1.ClientID %>").click(function() {
$("p").css("background-color", "Yellow")
});
When the Button renders on the client it won't have id = "Button1"
Change:
$("#Button1").click(function() {
to
$("#<%=Button1.ClientID%>").click(function() {
$("input[id$='Button1']").click(function() {
button click stuff here.
});

Setting focus onto another contol from button click

I am using ASP.NET 2.0 and VB.NET (C# code will also help me out)
On top of my page I have a button called btnViewRecords. When the User click on the button I want to set focus to another button or label further down on the same page. How can this be done.
This code does not work for me..............
btnTheRecords.Focus()
or
lblHeader.Focus()
Thanks in advance!!
Edit:
Even if my code did work, i dont want to reload the page every time.
Here's a relatively simple solution...
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick="return SetFocus()" />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<script type="text/javascript">
function SetFocus() {
document.getElementById('<%=TextBox2.ClientID %>').focus();
//or this if you're using jQuery
//$("#<%=TextBox2.ClientID %>").focus();
return false;
}
</script>
You can use JavaScript to do this.
document.getElementById ( "btnTheRecords" ).focus();
By setting focus what do you mean. Do you want to bring this control into view if it is way down the page. Then there are better ways to do this.
Edit:
You can place an anchor tag near the button or the bale and set
location.href = "#anchorId";
where anchorId is the id of the anchor tag.
will move the focus to the anchor tag.
Try this,
I wrote a small code and it seems to be working for me. sorry this is in C# but if you click on a button and set focus on another button then page will automatically scroll down for you.
ASP.NET
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
<div style="height:50px;"></div>
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" onclick="Button1_Click" />
</div>
<div style="height:1000px;"></div>
<div>
<asp:Button ID="Button2" runat="server" Text="Button 2" onclick="Button2_Click" />
</div>
</form>
</body>
</html>
AND Code Behind
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Button2.Focus();
Label1.Text = "button1 clicked & button2 in focus";
}
protected void Button2_Click(object sender, EventArgs e)
{
Button1.Focus();
Label1.Text = "button2 clicked & button1 in Focus";
}
}
I'm not sure exactly of the problem you're having. But in cases where the SetFocus() function and such just don't work (and they often don't in VB for some reason). I've often used workarounds such as shortcut Keys & mnemonics in combination with SendKeys() to get focus where I need it to be.
Depending on whether the buttons you are talking about are in your ASP.NET code or in your VB.NET code, this may be a viable workaround for you as well.
document.getElementById("spanId").scrollIntoView(false)
Reference:
.scrollIntoView
If the button is server side, set the "OnClientClick"
action on it to a javascript function. Cancel windows
events so the page location does not change.
function goto(){
window.event.cancelBubble = true;
window.event.returnValue = false;
document.getElementById("pageloction").focus()
}
asp:Button runat="server" ID="btnTheRecords" OnClientClick="javascript:goto()" />
span id="pageloction">

Categories

Resources