Disable server side of asp.net button - asp.net

How to disable button callback, I want to use this button on client side only?
<dx:ASPxButton ID="btn_clear" runat="server"
Text="Clear" Width="90px" OnClick="btn_clear_Click">
<ClientSideEvents Click = "OnClick" />
</dx:ASPxButton>

onClientClick=return false will prevent processing the normal postback. If you want to do some custome javascript at client side, you can call return false after that
<asp:Button id="btn1" runat="server" onClientClick="return MyFunction" />
And in javascript
function MyFunction()
{
//Do your custom code
return false;
}

Judging by your button tag prefix it looks as though you're using Devexpress components not a normal asp.net button. Devexpress' ASPxButton control client click event has a processOnServer property which you can set to false to prevent a postback:
<dx:ASPxButton ID="btn_clear" runat="server"
Text="Clear" Width="90px" OnClick="btn_clear_Click">
<ClientSideEvents Click = "OnClick" />
</dx:ASPxButton>
and your OnClick() javascript function:
function OnClick(s, e)
{
e.processOnServer = false;
}
Without using third party components, if you want a button to just do something client side, then just use a HTML input button but if you want to have the client side capabilities of the asp.net button at your disposal (such as causing validation) then Shyju's answer is the way to go.

Hwo about simply removing the OnClick Handler ?
<dx:ASPxButton ID="btn_clear" runat="server"
Text="Clear" Width="90px">
<ClientSideEvents Click = "OnClick" />
</dx:ASPxButton>
Or even better, just use a HTML button in the first place (<input type="button" />).

You can't.
Server side controls must run on the server side.
If you omit the runat="server" attribute, the markup will render exactly like this:
<dx:ASPxButton ID="btn_clear"
Text="Clear" Width="90px" OnClick="btn_clear_Click">
<ClientSideEvents Click = "OnClick" />
</dx:ASPxButton>
This will be completely ignored by the browser, as an element dx:ASPxButton is not a valid HTML element.

Just add an attribute AutoPostBack="false", this will stop the postback, still you need to call server side function using client side script, you can use callback panels

Related

asp OnClientClick not executing

This button:
<asp:Button ID="btnUpload" runat="server" Height="26px" Text="Upload" Width="86px" OnClick="btnUpload_Click" />
With added attribute in Page_Load:
btnUpload.Attributes.Add("OnClientClick", "javascript:alert('Test');")
Shows in browser Inspector:
<input type="submit" name="ctl00$MainContent$btnUpload" value="Upload" id="btnUpload" class="aspNetDisabled" onclientclick="javascript:alert('Test');" style="height:26px;width:86px;">
but never fires onClientClick. Tried calling function, preceding with 'javascript', many things.... but it never executes what's in onClientClick.
Note: The button's regular OnClick="btnUpload_Click" executes fine.
Any ideas?
This just adds a raw attribute to the resulting HTML:
btnUpload.Attributes.Add("OnClientClick", "javascript:alert('Test');")
And there is no OnClientClick in HTML, so the browser has no reason to make any use of it. That's something the ASP.NET server-side controls use and translate into client-side code. Add it directly to the server-side control instead:
<asp:Button
ID="btnUpload"
runat="server"
Height="26px"
Text="Upload"
Width="86px"
OnClick="btnUpload_Click"
OnClientClick="alert('Test');"
/>
Alternatively (and I don't have a way to test this at the moment), if it's a property on the control then you may be able to add it as such:
btnUpload.OnClientClick = "alert('Test');"
As an aside... If OnClientClick is continuing to cause problems then I'd recommend abandoning it altogether. (I honestly don't know why it even exists, other than as a vestige from a time when ASP.NET was trying to take the web out of web development.) If you just want to attach a click handler in JavaScript, you don't need C#'s permission to do that. Just attach a click handler in JavaScript:
const btn = document.querySelector('#btnUpload');
if (btn) {
btn.addEventListener('click', function () {
alert('Test');
});
}
Adding that to a <script> element at the end of the page would add that function as a click handler to the #btnUpload element.

How to use a custom ValidatorUpdateDisplay function when the controls / validators are loaded on postback in an UpdatePanel the first time?

In ASP.NET when using validation controls (i.e. RequiredFieldValidator) the client sided framework will execute the JS function Page_ClientValidate. This function will validate all controls on the page (of the given ValidationGroup) and call the JS function ValidatorUpdateDisplay with a parameter of the DOM element of the span tag of the validator control.
ValidatorUpdateDisplay toggles the visibility of the span tag depending on the result of the validation.
In my web application I've overridden the ValidatorUpdateDisplay JS function to provide more functionality on the validation scenario (i.e. red borders around the controls, showing popover on the first failed control and scrolling to it).
Now this works very well until my controls (incl. submit button) are shown the first time after a postback in an UpdatePanel.
<asp:ScriptManager runat="server" />
<asp:UpdatePanel ID="upTest" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="bShow" runat="server" UseSubmitBehavior="false" Text="SHOW" OnClick="bShow_Click" />
<asp:Panel ID="pContent" runat="server" Visible="false">
<asp:TextBox ID="tbTest" runat="server" />
<asp:RequiredFieldValidator ID="rfvTest" runat="server" ControlToValidate="tbTest" Text="Not valid" />
<asp:Button ID="bTest" runat="server" UseSubmitBehavior="false" Text="TEST" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
function ValidatorUpdateDisplay(val) {
debugger; // this will not be reached
}
</script>
protected void bShow_Click(object sender, EventArgs e)
{
this.pContent.Visible = true;
}
After initial load press bShow to display pContent.
Now, if you leave tbTest.Text empty and press on bTest it should enter the overridden ValidatorUpdateDisplay function, however it enters the function of the framework and displays "Not valid" from rfvTest.
If you change pContent.Visible to true and press bTest after initial load the desired effect will happen: It will enter the custom ValidatorUpdateDisplay function and not display "Not valid".
If you move the button bTest out of the UpdatePanel the problem persists.
How can I make it work inside an UpdatePanel?
ASP.NET uses a lazy loading approach to insert the ValidatorUpdateDisplay function when it needs it the first time, hence in my example it will load the function after the postback of the UpdatePanel.
This will override my own implementation of the ValidatorUpdateDisplay function, because it's inserting the function at the end of the page.
There is a dirty workaround, I just inserted an empty CustomValidator on initial load that is always valid:
<asp:CustomValidator runat="server" />
I wish there was a cleaner solution.

Can I create an ASP.NET ImageButton that doesn't postback?

I'm trying to use the ImageButton control for client-side script execution only. I can specify the client-side script to execute using the OnClientClick property, but how do I stop it from trying to post every time the user clicks it? There is no reason to post when this button is clicked. I've set CausesValidation to False, but this doesn't stop it from posting.
I know this problem has already been answered but a simple solution is to return false from the HTML onclick method (i.e. the ASPX OnClientClick method) e.g.
<asp:ImageButton ID="ImageNewLink" runat="server"
ImageUrl="~/images/Link.gif" OnClientClick="DoYourStuff(); return false;" />
Returning false stops the browser from making the request back to the server i.s. stops the .NET postback.
Here's one way you could do it without conflicting with the postback functioning of other controls:
Define your button something like this:
<asp:Button runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="alert('my client script here');my" />
The "my" ending in the handler for OnClientClick is a way to alias asp.net's __doPostBack client event that forces the postback; we simply override the behavior by doing nothing similar to this script:
<script type="text/javascript">
function my__doPostBack(eventTarget, eventArgument) {
//Just swallow the click without postback of the form
}
</script>
Edit: Yeesh, I feel like I need to take a shower after some of the dirty tricks that I need to pull in order to get asp.net to do what I want.
Another solution would be to define a PostBackUrl that does nothing
<asp:imagebutton runat="server" PostBackUrl="javascript:void(0);" .../>
<image src="..." onclick="DoYourThing();" />
Use a server side Image control
<asp:Image runat="server" .../>
Pretty sure you can add the client onclick event to that.
Solution 1
<asp:ImageButton ID="btn" runat="server" ImageUrl="~/images/yourimage.jpg"
OnClientClick="return false;" />
OR
Solution 2
<asp:ImageButton ID="btn" runat="server" ImageUrl="~/images/yourimage.jpg"
OnClientClick="yourmethod(); return false;" />
In addition (solution 2), your javascript method may be in this form
<script type="text/javascript">
function yourmethod() {
__doPostBack (__EVENTTARGET,__EVENTARGUMENT); //for example __doPostBack ('idValue',3);
}
</script>
in code behind
protected void Page_Load(object sender, System.EventArgs e)
{
if (this.IsPostBack) {
string eventTarget = this.Request("__EVENTTARGET") == null ? string.Empty : this.Request("__EVENTTARGET");
string eventArgument = this.Request("__EVENTARGUMENT") == null ? string.Empty : this.Request("__EVENTARGUMENT");
}
}
This works Great for me:
Use OnClientClick to write your script and PostBackUrl="javascript:void(0);" to avoid postback.
<div class="close_but">
<asp:ImageButton ID="imgbtnEChartZoomClose" runat="server" ImageUrl="images/close.png" OnClientClick="javascript:zoomclosepopup();" PostBackUrl="javascript:void(0);" />
</div>
Use OnClientClick to write your script and PostBackUrl="javascript:void(0);" to avoid postback

javascript __doPostBack doesn't seem to work for me

I use yui datatable in my asp.net application... I have a link button in one of my columns and it works fine but doesn't do a postback of a hidden button...
myDataTable.subscribe("linkClickEvent", function(oArgs) {
javascript: __doPostBack('ctl00_ContentPlaceHolder1_Button1', '');
YAHOO.util.Event.stopEvent(oArgs.event);
});
and in my page
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button"
style="display:none;" />
protected void Button1_Click(object sender, EventArgs e)
{
DownloadFile(Hfhref.Value, true);
}
I used break point but it doesn't seem to get the __dopostback.. Any suggestion...
add unique id on __doPostBackMethod from Button.
I just did this and it worked,
document.getElementById("ctl00_ContentPlaceHolder1_Button1").click();
just call click() my button it worked...
I want to know whether it works in all browsers...
If you're using ASP.Net 4.0 framework, add ClientIDMode="Static" to your control declaration and you can call __doPostBack('Button1',''); directly.
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button"
style="display:none;" ClientIDMode="Static" />
The ClientIDMode attribute is new to 4.0 and allows you the option of having a known unique id for controls. Calling postback for the control will run whatever postback method is defined in the control's OnClick attribute.
In your markup, make sure to properly case the OnClick handler.
onclick="Button1_Click"
should be
OnClick="Button1_Click"
The way you have written it, onclick will be interpreted as an attribute of the control and onclick="Button1_Click" will be rendered to the browser, instead of being handled on the server side.

OnClick vs OnClientClick for an asp:CheckBox?

Does anyone know why a client-side javascript handler for asp:CheckBox needs to be an OnClick="" attribute rather than an OnClientClick="" attribute, as for asp:Button?
For example, this works:
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
and this doesn't (no error):
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
but this works:
<asp:Button runat="server" OnClientClick="alert('Hi');" />
and this doesn't (compile time error):
<asp:Button runat="server" OnClick="alert('hi');" />
(I know what Button.OnClick is for; I'm wondering why CheckBox doesn't work the same way...)
That is very weird. I checked the CheckBox documentation page which reads
<asp:CheckBox id="CheckBox1"
AutoPostBack="True|False"
Text="Label"
TextAlign="Right|Left"
Checked="True|False"
OnCheckedChanged="OnCheckedChangedMethod"
runat="server"/>
As you can see, there is no OnClick or OnClientClick attributes defined.
Keeping this in mind, I think this is what is happening.
When you do this,
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
ASP.NET doesn't modify the OnClick attribute and renders it as is on the browser. It would be rendered as:
<input type="checkbox" OnClick="alert(this.checked);" />
Obviously, a browser can understand 'OnClick' and puts an alert.
And in this scenario
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
Again, ASP.NET won't change the OnClientClick attribute and will render it as
<input type="checkbox" OnClientClick="alert(this.checked);" />
As browser won't understand OnClientClick nothing will happen. It also won't raise any error as it is just another attribute.
You can confirm above by looking at the rendered HTML.
And yes, this is not intuitive at all.
Because they are two different kinds of controls...
You see, your web browser doesn't know about server side programming. it only knows about it's own DOM and the event models that it uses... And for click events of objects rendered to it. You should examine the final markup that is actually sent to the browser from ASP.Net to see the differences your self.
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
renders to
<input type="check" OnClick="alert(this.checked);" />
and
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
renders to
<input type="check" OnClientClick="alert(this.checked);" />
Now, as near as i can recall, there are no browsers anywhere that support the "OnClientClick" event in their DOM...
When in doubt, always view the source of the output as it is sent to the browser... there's a whole world of debug information that you can see.
You are right this is inconsistent. What is happening is that CheckBox doesn't HAVE an server-side OnClick event, so your markup gets rendered to the browser. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox_events.aspx
Whereas Button does have a OnClick - so ASP.NET expects a reference to an event in your OnClick markup.
For those of you who got here looking for the server-side OnClick handler it is OnCheckedChanged
I was cleaning up warnings and messages and see that VS does warn about it:
Validation (ASP.Net): Attribute 'OnClick' is not a valid attribute of element 'CheckBox'. Use the html input control to specify a client side handler and then you won't get the extra span tag and the two elements.
Asp.net CheckBox is not support method OnClientClick.
If you want to add some javascript event to asp:CheckBox you have to add related attributes on "Pre_Render" or on "Page_Load" events in server code:
C#:
private void Page_Load(object sender, EventArgs e)
{
SomeCheckBoxId.Attributes["onclick"] = "MyJavaScriptMethod(this);";
}
Note: Ensure you don't set AutoEventWireup="false" in page header.
VB:
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
SomeCheckBoxId.Attributes("onclick") = "MyJavaScriptMethod(this);"
End Sub
You can do the tag like this:
<asp:CheckBox runat="server" ID="ckRouteNow" Text="Send Now" OnClick="checkchanged(this)" />
The .checked property in the called JavaScript will be correct...the current state of the checkbox:
function checkchanged(obj) {
alert(obj.checked)
}
You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.
In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".
$(document).ready(function () {
$('input[type=checkbox]').click(function(){
var areYouSure = confirm('Are you sure you want make this change?');
if (areYouSure) {
$(this).prop('checked', this.checked);
} else {
$(this).prop('checked', !this.checked);
}
});
});
<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />
protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
using (myDataContext db = new myDataDataContext())
{
CheckBox chk = (CheckBox)sender;
RepeaterItem row = (RepeaterItem) chk.NamingContainer;
var studentID = ((Label) row.FindControl("lblID")).Text;
var z = (from b in db.StudentApplicants
where b.StudentID == studentID
select b).FirstOrDefault();
if(chk != null && chk.Checked != z.FinancialAid){
z.FinancialAid = chk.Checked;
z.ModifiedDate = DateTime.Now;
db.SubmitChanges();
BindGrid();
}
gvData.DataBind();
}
}
One solution is with JQuery:
$(document).ready(
function () {
$('#mycheckboxId').click(function () {
// here the action or function to call
});
}
);

Resources