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.
Related
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;
}
}
});
}
I thought this was straight forward, but i have a link button, and I do this in the click event:
myContainer.Controls.Add( new FileUpload());
I expect 1 new file control upload to be spawned in the container for each click, however, I always get 1. What do I need to do to have multiple file upload controls?
Since the control was added dynamically, it does not survive the postback. This means that you have to add the file upload (or any other dynamically added control) again in the preinit event to be able to have its values populated and to use it later on in the page life cycle.
Sounds like you are trying to be able to upload multiple files. You may want to add the file uploads with jQuery and use the Request.Files property to get them on the back-end.
I agree with Becuzz's answer. Try this, there are better ways to do it, but this might help as well:
Add this to the "Load" event of your page
if (!IsPostBack) {
Session["UploadControls"] = null;
}
if (Session["UploadControls"] != null) {
if (((List<Control>)Session["UploadControls"]).Count > 0) {
foreach ( ctrl in (List<Control>)Session["UploadControls"]) {
files.Controls.Add(ctrl);
}
}
}
And also add this to the PreInit portion of your page:
string ButtonID = Request.Form("__EVENTTARGET");
if (ButtonID == "Button1") {
FileUpload NewlyAdded = new FileUpload();
List<Control> allControls = new List<Control>();
if (Session["UploadControls"] != null) {
if (((List<Control>)Session["UploadControls"]).Count > 0) {
foreach ( ctrl in (List<Control>)Session["UploadControls"]) {
allControls.Add(ctrl);
//Add existing controls
}
}
}
if (!allControls.Contains(NewlyAdded)) {
allControls.Add(NewlyAdded);
}
Session["UploadControls"] = allControls;
}
And add this to your HTML. This can be anything of course:
<div id="files" runat="server">
</div>
I use the "__EVENTTARGET" value to know what caused the postback, so that you don't get unwanted Upload controls.
Good luck, and hopefully this helps.
Hanlet
What I would like to do is have the user add a new record to the database and popup a JQuery dialog confirming that the new record was saved. I thought this would be a simple exercise. I have a gridview bound to a LINQDataSource to allow the user to view and edit existing records and a textbox and a button to add new codes.
In the head of the document, I have the following:
$('#dialog').dialog({
autoOpen: false,
width: 400,
buttons: {
"Ok": function () {
$(this).dialog("close");
}
}
});
and futher down in the markup I have:
<div id="dialog" title="New Code Added">
<p>"<asp:Literal runat="server" ID="LiteralNewCode"></asp:Literal>" was successfully added.</p>
</div>
So when the user enters a new description and it passes all the validation, it's added to the database and the gridview is rebound to display the new record.
protected void ButtonSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
CCRCode.Add( <long list of paramters> );
GridCode.DataBind();
IsNewCode = true;
NewDescription = <new description saved to database>;
}
}
Now, here's where (I thought) I'd set a boolean property to indicate that a new description had been added as well as the text of the new description. See below:
protected bool IsNewCode
{
get { return ViewState["IsNewCode"] != null ? (bool)ViewState["IsNewCode"] : false; }
set { ViewState["IsNewCode"] = value; }
}
private string NewDescription
{
get { return ViewState["NewDescription"] != null ? ViewState["NewDescription"].ToString() : string.Empty; }
set { ViewState["NewDescription"] = value; }
}
Here's where I loose my way. My guess is I want to add functionality to include code similar to:
$('#dialog').dialog('open');
I've added a registerscriptblock method in the page_load event but that didn't work. Any ideas? Or am I just going about this entirely wrong?
Thanks.
Not really get what you want to do. But, i use jquery alot with .NET in my projects. here is how i do, probably could give you a hint.
foo.aspx.cs
public String ScriptToRun = "$('#dialog').dialog('open');";
change the value of ScriptToRun in your C# code
foo.aspx
$(document).ready(function() {<%=ScriptToRun %>});
Remember that whatever you done in backend is going to generate HTML, Css& javascript to browser.
Two ways: one, write the javascript in your server-side code. Or, define a JS method to show the dialog (say named showDialog), and call it via:
Page.ClientScript.RegisterStartupScript(... "showDialog();" ..);
RegisterStartupScript puts the method call at the end, ensure your script is above it to work. You can also wrap it with document.ready call too, to ensure JQuery is properly loaded.
I think that the only think that you have miss is the creation of the dialog when the Dom is ready.
$(document).ready(function() {$('#dialog').dialog('open');});
I posted code in a different question for a custom "MessageBox" class I wrote:
ASP.NET Jquery C# MessageBox.Show dialog uh...issue
the code by default uses the javascript alert() function, but you can define your callback so that it calls your custom javascript method to display the messages.
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.
I have an ASP.NET user control (.ascx file). In this user control I want to use a .js file.
So I include <script src="file.js" type"text/javascript"></script> on the page.
However, sometimes I use this user control in a webpage where this same script has already been loaded.
How can I add a <script /> declaration that will render on the page only if the page doesn't already contain another <script /> tag for the same script?
As you are using asp.net, it makes sense to do the check server-side as that will be where you choose to add the reference to the javascript file. From your .ascx file you could register with the following:
this.Page.ClientScript.RegisterClientScriptInclude("GlobalUnqiueKey", UrlOfJavascriptFile);
... from your page you just call the ClientScript object directly:
ClientScript.RegisterClientScriptInclude("GlobalUnqiueKey", UrlOfJavascriptFile);
The 'GlobalUniqueKey' can be any string (I use the url of the javascript file for this too)
If you try to register a script with the same key string, it doesn't do anything. So if you call this in your page, your control or anywhere else, you'll end up with only one reference in your page. The benefit of this is that you can have multiple instances of a control on a page and even though they all try to register the same script, it is only ever done a maximum of one time. And none of them need to worry about the script being already registered.
There is a 'IsClientScriptIncludeRegistered(stringkey)' method which you can use to see if a script has already been included under that key but it seems pretty redundant to do that check before registering as multiple attempts to register do not throw exceptions or cause any other errors.
Doing the check client-side means that, assuming the multiple javascript references are cached by the browser (they may not be), you still have multiple tags and the over head of each one causing some javascript to run. If you had 20 instances of your control on a page, you could get serious issues.
You can do one of two things client side...
Check the dom for the script tag corresponding to the javascript file your want to check
Test a variable or function you know has/will be defined within the javascript file for undefined.
Here's a quick JS function which uses JQuery to do what you need:
function requireOnce(url) {
if (!$("script[src='" + url + "']").length) {
$('head').append("<script type='text/javascript' src='" + url + "'></script>");
}
}
use something like the following:
if(typeof myObjectOrFunctionDecalredInThisScript != 'undefined') {
// code goes here
var myObjectOrFunctionDecalredInThisScript = { };
}
This tests if your object or function already exists and thus prevents redeclaration.
var storePath = [];
function include(path){
if(!storePath[path]){
storePath[path]= true;
var e = document.createElement("script");
e.src = path;
e.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(e);
return false;
} }
use this in your main page and call function include with argument javascript file name
As you want to include javascript on one page of your site only.
If you use Asp.net(4.0) then it is very easy.
Just include following code
<script type="text/javascript" scr="filepath and name here"></script>
in ContentPlaceHolder of content page.
#Shimmy I am coming across this after a long while but maybe it might still be useful or at least help other coming from behind. To check if jquery is already loaded do this
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.x.x.min.js"><\/script>')</script>
Don't miss the escape character in the closing script tag in document.write statement.
#mysomic, why did I not think of that. thumbs up
PS: I would have loved to write this right under the line where #Shimmy wrote that jQuery itself is the script he wants to load. But dont know how to write it there. cant see a reply or anything similar link. This may sound dumb but maybe I'm missing something. Pls point it out, anybody?
If you need it from server side, and Page.ClientScript.RegisterClientScriptInclude won't work for you in case script was included by some other way other then Page.ClientScript.RegisterClientScript (for example page.Header.Controls.Add(..), you can use something like this:
static public void AddJsFileToHeadIfNotExists(Page page, string jsRelativePath)
{
foreach (Control ctrl in page.Header.Controls)
{
if (ctrl is HtmlLink htmlLink)
{
if (htmlLink.Href.ToLower().Contains(jsRelativePath.ToLower())) return;
}
if (ctrl is ITextControl textControl
&& (textControl is LiteralControl || textControl is Literal))
{
if (textControl.Text.ToLower().Contains(jsRelativePath.ToLower())) return;
}
if (ctrl is HtmlControl htmlControl)
{
if (htmlControl.Attributes["src"]?.ToUpper()
.Contains(jsRelativePath.ToUpper())) return;
}
}
HtmlGenericControl Include = new HtmlGenericControl("script");
Include.Attributes.Add("type", "text/javascript");
Include.Attributes.Add("src", page.ResolveUrl(jsRelativePath));
page.Header.Controls.Add(Include);
}