How to set UseSubmitBehavior="False" in one place for the whole web application - asp.net

I want all of the buttons in my asp.net web forms application to have UseSubmitBehavior="False" but I don't want to go through all my pages trying to hunt down each and every last button and set the property individually.
I am hoping there is a way to do this globally, for example in the web.config file. Thanks!

This is not a page property or something like that
this is a button property which allowes submit via __doPostBack
You Can't do this globally via web.config ( or in any other way).

The reason for wanting to set UseSubmitBehavior="False" is to stop the form from submitting when the user presses enter. If this is your goal then the following will interest you:
Another way to do this is to use JavaScript. This shifts the overhead of MikeSmithDev's suggestion to the client which might be more acceptable depending on your scenario.
Please note that the following JavaScript makes use of the jQuery library:
$(document).ready(function () {
preventSubmitOnEnter();
});
function preventSubmitOnEnter() {
$(window).keypress(function (e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
return false;
}
}
});
}

Related

bootstrap studio: enter key appears to causing reload of page

I have a web page with several forms. Only one is visible at a time, depending on state.
On one form, pressing the enter key appears to be causing a reload of the page rather than triggering a click event for the form's button.
I have a lot of javascript, primarily because I need client side interaction with mailchimp. Because of that, I have disabled the form's action= html and have instead created a javascript function to handle the click. It works fine if you click on the button.
I have also assigned a listener for the sole field in the form:
var input = document.getElementById ("new-email-address");
input.addEventListener ("keyup", function(event)
{
if (event.keyCode === 13)
{
event.preventDefault();
document.getElementById("new-email-address").click();
}
});
Yet, when I click the enter key, the $(document).ready (function() executes. It's possible something else is executing beforehand, but, if so, I haven't found a way to discover that.
What could be causing this behavior ?
It turns out that the enter key is being handled at the form level. To disable that, I added this code for each form:
$("#the-form").keypress(function(e)
{
if (e.which == 13) // Enter key
return false;
});

AsyncFileUpload control

Regarding the AsyncFileUpload control in .net, the control will execute the file upload once i select a file. In my concern is, is it possible to disable the upload once i select a file so that i could process the upload asynchronously with a submit button.
I know this is old, but I beat my head on this for a while, so for whoever might be interested.
My first thought was to disable the file input underneath the control.
I was able to disable the control but unfortunately, it stopped working. When the server fired AsyncFileUpload_UploadComplete the input was diabled so there wasn't a file to read.
<script>
function disableFileUpload(on) {
if (on) {
$('#ajax-file-input input:file').attr('disabled', true);
} else {
$(#ajax-file-input 'input:file').attr('disabled', false);
}
}
function AsyncFileUpload_CheckExtension(sender, args) {
disableFileUpload(true);
return true;
}
function AsyncFileUpload_OnClientUploadComplete(sender, args) {
disableFileUpload(false);
var data = eval('(' + args.d + ')');
for (var key in data) {
var obj = data[key];
for (var prop in obj) {
console.log(prop + " = " + obj[prop]);
}
}
doThingsWith(data);
}
</script>
<div id="ajax-file-input">
<ajaxToolkit:AsyncFileUpload ID="AsyncFileUpload1"
OnUploadedComplete="AsyncFileUpload_UploadComplete"
OnClientUploadStarted="AsyncFileUpload_CheckExtension"
OnClientUploadComplete="AsyncFileUpload_OnClientUploadComplete"
runat="server" />
</div>
I ended up positioning a semi-transparent png on top of the control and showing and hiding it to make the control innaccesible.
Hope this helps.
function disableFileUpload(on) {
if (on) {
$("#file-disabled").show();
} else {
$("#file-disabled").hide();
}
}
Simple answer is No. I've had similar asyncupload issues just like those ones. My advice is to stay away from him if you need to control upload with a button, add and remove selected files (you will probably need this later on) and use some javascript manipulation.
Search for the SWFUpload, is a flash component that can be integrated with .NET with ease. It offers multiple javascript options and events. :D
Check the following links:
Official site
Demonstration
As far as I know that the only event exposed by AsyncFileUpload is the UploadComplete event and UploadError. There aren't events specifically that expose functionality to manually initiate the upload. Perhaps some trick in JavaScript could do it but I have not seen such a workaround before.

C# .NET and Javascript Confirm

I have a C# ASP.NET web page with an xml file upload form. When the user clicks 'upload', a javascript confirm alert will pop up asking the user, "is this file correct?". The confirm alert will only activate if the file name does not contain a value from one of the other form fields.
What is the best way to combine the use of a C# ASP.NET form and a javascript confirm alert that is activated if the name of a file being uploaded does not meet certain criteria?
There's not much you need to do with C# for this page, it sounds like most of this will be done on the client side.
Add the fileupload control and a button to your .aspx form. Set the Button's OnClientClick property to something like
OnClientClick = "return myFunction()"
and then write a javascript function like:
function myFunction()
{
// Check other text values here
if (needToConfirm){
return confirm('Are you sure you want to upload?');
}
else return true;
}
Make sure "myFunction()" returns false if you wish to cancel the postback (i.e. the user clicked "no" in the confirm dialog). This will cancel the postback if they click "No".
I suppose you are putting value of valid string in a hidden field (you haven't mentioned). Implement OnClientClick for Upload button:
<asp:button .... OnClientClick="return confirmFileName();"/>
<script type="text/javascript">
function confirmFileName()
{
var f = $("#<%= file1.ClientID %>").val();
var s=$("#<%= hidden1.ClientID %>").attr("value");
if (f.indexOf(s) == -1) {
if (!confirm("Is this correct file?")) {
$("#<%=file1.ClientID %>").focus();
return false;
}
}
return true;
}
</script>
EDIT:- Regarding <%= file1.ClientID %>.
This will be replaced by the client side ID of the file upload control like ctl00$ctl00$cphContentPanel$file1. It puts the script on steroids with respect to using something like $("input[id$='file1']"). For more information please see Dave Wards' post.
window.onload = function() {
document.forms[0].onsubmit = function() {
var el = document.getElementById("FileUpload1");
var fileName = el.value;
if(fileName.indexOf("WHATEVER_VALUE") == -1) {
if(!confirm("Is the file correct?")) {
el.focus();
return false;
}
}
return true;
}
}
I had problems implementing this kind of thing to work in both IE and FireFox because of the way events work in those browsers. When I got it to work in one of them, the other would still cause a postback even if I cancelled out.
Here's what we have in our code (the browser test was stolen from elsewhere).
if (!window.confirm("Are you sure?"))
{
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
window.event.returnValue = false;
else
e.preventDefault();
}
In addition to using client side validation, you should also add a CustomValidator to provide validation on the server side. You cannot trust that the user has Javascript turned on, or that the user has not bypassed your Javascript checks.

disable asp.net validator using jquery

I am trying to disable validators using jquery.
I have already looked
Disable ASP.NET validators with JavaScript
and couple of others doing the same.
It seems ot be working but its breaking.
My code:
$('.c_MyValdiators').each(function() {
var x = $(this).attr('id');
var y = document.getElementById(x);
ValidatorEnable(y[0], false);
});
I get Error:
val is undefined
[Break on this error] val.enabled = (enable != false);\r\n
Alternatively if I use
$('.c_MyValdiators').each(function() {
ValidatorEnable($(this), false); OR ValidatorEnable($(this[0]), false);
});
I get Error:
val.style is undefined
[Break on this error] val.style.visibility = val.isvalid ? "hidden" : "visible";\r\n
Any idea or suggestions?
I beleive that ValidatorEnable takes the ASP.net ID rather that the ClientID produced by ASP.net. You will also need to make the validation conditional in the CodeBehind.
here is an example:
Of particular use is to be able to enable or disable validators. If you have validation that you want active only in certain scenarios, you may need to change the activation on both server and client, or you will find that the user cannot submit the page.
Here is the previous example with a field that should only be validated when a check box is unchecked:
public class Conditional : Page {
public HtmlInputCheckBox chkSameAs;
public RequiredFieldValidator rfvalShipAddress;
public override void Validate() {
bool enableShip = !chkSameAs.Checked;
rfvalShipAddress.Enabled = enableShip;
base.Validate();
}
}
Here is the client-side equivalent:
<input type=checkbox runat=server id=chkSameAs
onclick="OnChangeSameAs();" >Same as Billing<br>
<script language=javascript>
function OnChangeSameAs() {
var enableShip = !event.srcElement.status;
ValidatorEnable(rfvalShipAddress, enableShip);
}
</script>
Reference: http://msdn.microsoft.com/en-us/library/aa479045.aspx
I just stumbled upon your Question [a year later].
I too wanted to disable all validators on a page using JQuery here is how I handled it.
$('span[evaluationfunction]').each(function(){ValidatorEnable(this,false);});
I look for each span on the page that has the evaluatefunction attribute then call ValidatorEnabled for each one of them.
I think the $('this') part of your code is what was causing the hickup.
ValidatorEnable(document.getElementById($(this).attr('id')), true);
I've got another solution, which is to use the 'enabled' property of the span tag for the validator. I had different divs on a form that would show or hide so I needed to disable the validation for the fields inside the hidden div. This solution turns off validation without firing them.
If you have a set of RequiredFieldvalidator controls that all contain a common string that you can use to grab them the jquery is this:
$("[id*='CommonString']").each(function() {
this.enabled = false; // Disable Validation
});
or
$("[id*='CommonString']").each(function() {
this.enabled = true; // Enable Validation
});
Hope this helps.
John
I'm just running into the same problem, thanks to the other answers, as it helped uncover the problem, but they haven't gone into detail why.
I believe it is due to that ValidatorEnable() expects a DOM object (i.e. the validation control object) opposed to an ID.
$(selector).each() sets "this" to the DOM element being currently iterated over i.e. quoted from the jquery documentation:
"More importantly, the callback is fired in the context of the current
DOM element, so the keyword this refers to the element." - http://api.jquery.com/each/
Therefore you do not need to do: document.getElementById($(this).attr('id')
And instead ValidatorEnable(this, true); is fine.
Interestingly, Russ's answer mentioned needing to disable server side validation as well, which does make sense - but I didn't need to do this (which is concerning!).
Scrap my previous comment, it is because I had my control disabled server-side previously.
The ValidatorEnable function takes an object as the 1st parameter and not a string of the id of the object.
Here is the simple way to handle this.
Add a new class to the Validation control.
Then look for that class with jquery and disable the control.
Example :
if (storageOnly == 1)
{
$('#tblAssignment tr.assdetails').addClass('hidden');
$('span[evaluationfunction]').each(function ()
{
if ($(this).hasClass('assdetail'))
{ ValidatorEnable(this, false); }
});
}
else
{
$('#tblAssignment tr.assdetails').removeClass('hidden');
}
* Works like a charm.
** For you imaginative types, assdetail == assignment detail.
Here depending on the if condition, I am either hiding the rows then disabling the validator , or removing hidden class from the rows..
Various ways to this depending on your needs. Some solutions in the following blog posts:
http://imjo.hn/2013/03/28/javascript-disable-hidden-net-validators/
http://codeclimber.net.nz/archive/2008/05/14/How-to-manage-ASP.NET-validation-from-Javascript-with-jQuery.aspx

How do I interrupt an ASP.NET button postback with BlockUI and Jquery

I have an ASP.NET page with a number of ASP:Button instances on it. For some, I need to show a confirmation prompt and, should the user choose yes, the original postback method is called. Otherwise, the overall process is cancelled.
I've got an example running but I get inconsistent results, mainly in FF3 where I get an exception thrown:
[Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame ::
I've looked this error up but I'm drawing a loss as to where I'm going wrong. Here's my example case. Note, for now I'm just using the css class as a lookup. Longer term I can embed the clientID of the control into my JS if it proves necessary :).
Html fragment:
<asp:Button ID="StartButton" runat="server" CssClass="startbutton" Text="Start" OnClick="OnStartClicked" />
Javascript:
$(".startbutton").each(function(){
$(document).data("startclick", $(this).get()[0].click);
$(this).unbind("click");
}).click(function(){
var oldclick = $(document).data("startclick");
alert("hello");
try
{
oldclick();
}
catch(err)
{
alert(err);
alert(err.description);
}
return false;
});
My code behind is relatively simple, the OnStart method simply executes a Response.Write
I've only just started looking into bind, unbind and trigger so my usage here is pretty much 'first time'.
Thanks for any help or advice.
S
EDIT:
This describes what I'm trying to do and also gives a run down of the kind of pitfalls:
http://www.nabble.com/onClick-prepend-td15194791s27240.html
How about this?
$(document).ready( function() {
$('.startbutton').click(function() {
return confirm('Are you sure?');
})
});
I've solved my problem for IE7 and FF3.
The trick is to make the postback work as an 'onclick' via an ASP.NET attribute on the button (see below). In Javascript this gets pulled out as a function reference when you read the click in JQuery.
To make it work, you then clear the onclick attribute (after saving it) and call it later on.
My code below shows it in action. This code isn't complete as I'm part way through making this into a generic prompt for my application. Its also a bit badly laid out! But at least it shows the principle.
ASP.NET button
<asp:Button ID="StartButton" runat="server" CssClass="startbutton" Text="Start" OnClick="OnStart" UseSubmitBehavior="false" />
Javascript:
$(".startbutton").each(function(){
$(document).data("startclick", $(this).attr("onclick"));
$(this).removeAttr("onclick");
}).click(function(){
$.blockUI({ message: $('#confirm'), css: { width: '383', cursor: 'auto' } });
$("#yes").click(function(){
$.unblockUI();
var oldclick = $(document).data("startclick");
try
{
oldclick();
}
catch(err)
{
alert(err);
alert(err.description);
}
});
$("#no").click(function(){
$.unblockUI();
});
return false;
});
Your problem comes from here :
$(document).data("startclick", $(this).get()[0].click);
...
var oldclick = $(document).data("startclick");
...
oldclick();
Here, you try to intercept a native event listener but there are two errors :
Using unbind will not remove the native event listener, just the ones added with jQuery
click is, AFAIK, a IE only method used to simulate a click, it not the event handler itself
You'll have to use onclick instead set its value to null instead of using unbind. Finally, don't store it in $(document).data(...), you'll have some problems when you add other buttons. Here is a sample code you can use :
$("selector").each(function()
{
var oldclick = this.onclick;
this.onclick = null;
$(this).click(function()
{
if (confirm("yes or no ?")) oldclick();
});
});
for mi works:
this.OnClientClick = "$.blockUI({ message: $('#ConfirmacionBOX'), css: { width: '275px' } });return false;";
This is a button (is a button class)

Resources