AJAX javascript not firing asp.net c# - c#

When I add new controls to my web application, the javascript does not fire. I've tried many solutions, but none of them work. Specifically, the accordion/accordion pane from the AJAX Control Toolkit does not slide up/down. Also the FileUploadProgress control from Obout uses javascript functions which do not fire. If I open a new web application project and try all this, it works just fine. My project is quite large so I cannot start from scratch. Can someone please tell me what could be wrong with my project? I have no errors. The javascript simply does not fire. Please help. I am using asp.net c#.
EDIT:
Here is the code for file upload progress control. I do have alert statements but they do not fire.
<script type="text/JavaScript">
function Clear() {
alert("here1");
document.getElementById("<%= uploadedFiles.ClientID %>").innerHTML = "";
}
function ClearedFiles(fileNames) {
alert("here2");
alert("Cleared files with bad extensions:\n\n" + fileNames);
}
function Rejected(fileName, size, maxSize) {
alert("here3");
alert("File " + fileName + " is rejected \nIts size (" + size + " bytes) exceeds " + maxSize + " bytes");
}
</script>
<input type="file" name="myFile1" runat="server"/><br/>
<input type="file" name="myFile2" runat="server"/><br/>
<input type="file" name="myFile3" runat="server"/><br/>
<input type="submit" value="submit" name="mySubmit" /><br/>
<br/>
<fup:FileUploadProgress ID="FileUploadProgress1"
OnClientProgressStopped = "function(){alert('Files are uploaded to server');}"
OnClientProgressStarted = "Clear"
ShowUploadedFiles = "true"
OnClientFileRejected = "Rejected"
OnClientFileCleared = "ClearedFiles"
runat = "server"
>
<AllowedFileFormats>
<fup:Format Ext="gif" MaxByteSize="10240"/>
<fup:Format Ext="jpg" MaxByteSize="10240"/>
<fup:Format Ext="jpeg" MaxByteSize="10240"/>
<fup:Format Ext="png" MaxByteSize="10240"/>
</AllowedFileFormats>
</fup:FileUploadProgress>
<asp:Label runat="server" id="uploadedFiles" Text="" />
And here's the code-behind for it:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
HttpFileCollection files = Page.Request.Files;
uploadedFiles.Text = "";
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (file.FileName.Length > 0)
{
if (uploadedFiles.Text.Length == 0)
uploadedFiles.Text += "<b>Successfully uploaded files: </b><table border=0 cellspacing=0>";
uploadedFiles.Text += "<tr><td class='option2'>" + file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1) + "</td><td style='font:11px Verdana;'> " + file.ContentLength.ToString() + " bytes</td></tr>";
}
}
if (uploadedFiles.Text.Length == 0)
uploadedFiles.Text = "no files";
else
uploadedFiles.Text += "</table>";
}
}
Thanks in advance!!

Looks like it is because you are passing anything to your javascript functions. :
Here is what you have. :
OnClientProgressStarted = "Clear"
ShowUploadedFiles = "true"
OnClientFileRejected = "Rejected"
OnClientFileCleared = "ClearedFiles"
Here is what I think you should probably have. :
OnClientProgressStarted = "Clear();"
ShowUploadedFiles = "true"
OnClientFileRejected = "Rejected();"
OnClientFileCleared = "ClearedFiles();"
Also, several of those functions require parameters, which I did not list above......Hopefully this helps you.

Related

HtmlAgilityPack : Is there a better way to write this

I recently started experimenting with HtmlAgilityPack, and the following code is working for what I want to achieve.
But since I just started exploring this, I was wondering if there was a better way then using so many PreviousSibling tags
var Application_Html = #"https://wiki.profittrailer.com/doku.php?id=application.properties";
HtmlWeb Internet_Load_Connection = new HtmlWeb();
var Application_Html_Loaded = Internet_Load_Connection.Load(Application_Html);
var Wiki_Application_Part_Loaded = Application_Html_Loaded.DocumentNode.SelectSingleNode("//div[#class ='dw-content']");
var divs = Application_Html_Loaded.DocumentNode.Descendants("div").Where(node => node.GetAttributeValue("class", "").Equals("level5")).Where(node => node.ParentNode.GetAttributeValue("class", "").Equals("dw-content")).ToList();
foreach (var s in divs)
{
if (s.InnerText.IndexOf(" ") > 0)
{
if (s.PreviousSibling.PreviousSibling.Id.Contains("default_api") || s.PreviousSibling.PreviousSibling.Id.Contains("trading_api"))
{
textBox1.AppendText(s.PreviousSibling.PreviousSibling.PreviousSibling.PreviousSibling.PreviousSibling.PreviousSibling.Id + "\n");
textBox1.AppendText(s.PreviousSibling.PreviousSibling.PreviousSibling.PreviousSibling.PreviousSibling.PreviousSibling.InnerText + "\n");
textBox1.AppendText(s.ChildNodes[3].InnerText + "\n");
textBox1.AppendText("\n");
textBox1.AppendText(s.PreviousSibling.PreviousSibling.Id + "\n");
textBox1.AppendText(s.PreviousSibling.PreviousSibling.InnerText + "\n");
textBox1.AppendText(s.ChildNodes[3].InnerText + "\n");
textBox1.AppendText("\n");
}
else
{
textBox1.AppendText(s.PreviousSibling.PreviousSibling.Id + "\n");
textBox1.AppendText(s.PreviousSibling.PreviousSibling.InnerText + "\n");
textBox1.AppendText(s.ChildNodes[3].InnerText + "\n");
textBox1.AppendText("\n");
}
}
}
The idea behind this is to scrape the wiki to see if anything has changed and if so to update/notify me if changes are needed.
Example html piece for reference
<h5 id="tradingexchange">trading.exchange</h5>
<div class="level5">
<pre class="code file java">trading.<span class="me1">exchange</span> <span
class="sy0">=</span> BITTREX</pre>
<p>
Use to set the exchange you want the bot to connect to. Possible values
(POLONIEX, BITTREX, BINANCE).
Must be in CAPITALS.
</p>
<hr />
</div>
all is in the div class="dw-content" which I extract first
h5 id is needed to check if new option are added
h5 innertext is need to check the formatting
p innertext to check if the description is updated or not

Creating a file upload feature without jquery or ajax

I have to create a file upload that only allows .csv files. So far, I have a cosmetic interface of:
<asp:Label ID="importLabel" runat="server" Text="Update Prices" CssClass="fieldLabel" />
<asp:FileUpload ID="importFileUpload" runat="server" OnDataBinding="importFileUpload_DataBinding"/>
<asp:Button ID="importFileButton" runat="server" Text="Update Prices" CssClass="fieldlabel" OnClick="importFileButton_Click" />
<br />
<asp:RegularExpressionValidator ID="uploadValidator" runat="server" ControlToValidate="importFileUpload" ErrorMessage="Only .csv files are allowed"
ValidationExpression="(.+\.([Cc][Ss][Vv]))" />
It works as it should where you can select a .csv file, however I'm not sure of my next step here. Any help or any nudge in the right direction would be awesome!
The next step is uploading the selected file from the code behind:
protected void importFileButton_Click(object sender, EventArgs e)
{
if (importFileUpload.HasFile)
{
string fileExt =
System.IO.Path.GetExtension(importFileUpload.FileName);
if (fileExt == ".csv")
{
try
{
importFileUpload.SaveAs("C:\\Uploads\\" + importFileUpload.FileName);
importLabel.Text = "File name: " +
importFileUpload.PostedFile.FileName + "<br>" +
importFileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
importFileUpload.PostedFile.ContentType;
}
catch (Exception ex)
{
importLabel.Text = "ERROR: " + ex.Message.ToString();
}
}
else
importLabel.Text = "Only .csv files allowed!";
}
else
importLabel.Text = "You have not specified a file.";
}
I have used dropzone.js before for this specific purpose. It does not require jquery. You should be able to do something like this below:
Dropzone.options.filedrop = {
acceptedMimeTypes: 'text/csv',
}
See this question on implementation for limiting specific mime types.

File Size Validation [duplicate]

Is there any way to check file size before uploading it using JavaScript?
Yes, you can use the File API for this.
Here's a complete example (see comments):
document.getElementById("btnLoad").addEventListener("click", function showFileSize() {
// (Can't use `typeof FileReader === "function"` because apparently it
// comes back as "object" on some browsers. So just see if it's there
// at all.)
if (!window.FileReader) { // This is VERY unlikely, browser support is near-universal
console.log("The file API isn't supported on this browser yet.");
return;
}
var input = document.getElementById('fileinput');
if (!input.files) { // This is VERY unlikely, browser support is near-universal
console.error("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
addPara("Please select a file before clicking 'Load'");
} else {
var file = input.files[0];
addPara("File " + file.name + " is " + file.size + " bytes in size");
}
});
function addPara(text) {
var p = document.createElement("p");
p.textContent = text;
document.body.appendChild(p);
}
body {
font-family: sans-serif;
}
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load'>
</form>
Slightly off-topic, but: Note that client-side validation is no substitute for server-side validation. Client-side validation is purely to make it possible to provide a nicer user experience. For instance, if you don't allow uploading a file more than 5MB, you could use client-side validation to check that the file the user has chosen isn't more than 5MB in size and give them a nice friendly message if it is (so they don't spend all that time uploading only to get the result thrown away at the server), but you must also enforce that limit at the server, as all client-side limits (and other validations) can be circumvented.
Using jquery:
$('#image-file').on('change', function() {
console.log('This file size is: ' + this.files[0].size / 1024 / 1024 + "MiB");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form action="upload" enctype="multipart/form-data" method="post">
Upload image:
<input id="image-file" type="file" name="file" />
<input type="submit" value="Upload" />
</form>
Works for Dynamic and Static File Element
Javascript Only Solution
function validateSize(input) {
const fileSize = input.files[0].size / 1024 / 1024; // in MiB
if (fileSize > 2) {
alert('File size exceeds 2 MiB');
// $(file).val(''); //for clearing with Jquery
} else {
// Proceed further
}
}
<input onchange="validateSize(this)" type="file">
It's pretty simple.
const oFile = document.getElementById("fileUpload").files[0]; // <input type="file" id="fileUpload" accept=".jpg,.png,.gif,.jpeg"/>
if (oFile.size > 2097152) // 2 MiB for bytes.
{
alert("File size must under 2MiB!");
return;
}
No Yes, using the File API in newer browsers. See TJ's answer for details.
If you need to support older browsers as well, you will have to use a Flash-based uploader like SWFUpload or Uploadify to do this.
The SWFUpload Features Demo shows how the file_size_limit setting works.
Note that this (obviously) needs Flash, plus the way it works is a bit different from normal upload forms.
If you're using jQuery Validation, you could write something like this:
$.validator.addMethod(
"maxfilesize",
function (value, element) {
if (this.optional(element) || ! element.files || ! element.files[0]) {
return true;
} else {
return element.files[0].size <= 1024 * 1024 * 2;
}
},
'The file size can not exceed 2MiB.'
);
I made something like that:
$('#image-file').on('change', function() {
var numb = $(this)[0].files[0].size / 1024 / 1024;
numb = numb.toFixed(2);
if (numb > 2) {
alert('to big, maximum is 2MiB. You file size is: ' + numb + ' MiB');
} else {
alert('it okey, your file has ' + numb + 'MiB')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="file" id="image-file">
Even though the question is answered, I wanted to post my answer. Might come handy to future viewers.You can use it like in the following code.
document.getElementById("fileinput").addEventListener("change",function(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
alert("Got the file\n" +
"name: " + f.name + "\n" +
"type: " + f.type + "\n" +
"size: " + f.size + " bytes\n" +
"starts with: " + contents.substr(1, contents.indexOf("\n"))
);
if (f.size > 5242880) {
alert('File size Greater then 5MiB!');
}
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
})
<input type="file" id="fileinput" />
I use one main Javascript function that I had found at Mozilla Developer Network site https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications, along with another function with AJAX and changed according to my needs. It receives a document element id regarding the place in my html code where I want to write the file size.
<Javascript>
function updateSize(elementId) {
var nBytes = 0,
oFiles = document.getElementById(elementId).files,
nFiles = oFiles.length;
for (var nFileId = 0; nFileId < nFiles; nFileId++) {
nBytes += oFiles[nFileId].size;
}
var sOutput = nBytes + " bytes";
// optional code for multiples approximation
for (var aMultiples = ["K", "M", "G", "T", "P", "E", "Z", "Y"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
sOutput = " (" + nApprox.toFixed(3) + aMultiples[nMultiple] + ")";
}
return sOutput;
}
</Javascript>
<HTML>
<input type="file" id="inputFileUpload" onchange="uploadFuncWithAJAX(this.value);" size="25">
</HTML>
<Javascript with XMLHttpRequest>
document.getElementById('spanFileSizeText').innerHTML=updateSize("inputFileUpload");
</XMLHttpRequest>
Cheers
JQuery example provided in this thread was extremely outdated, and google wasn't helpful at all so here is my revision:
<script type="text/javascript">
$('#image-file').on('change', function() {
console.log($(this)[0].files[0].name+' file size is: ' + $(this)[0].files[0].size/1024/1024 + 'Mb');
});
</script>
I ran across this question, and the one line of code I needed was hiding in big blocks of code.
Short answer: this.files[0].size
By the way, no JQuery needed.
You can try this fineuploader
It works fine under IE6(and above), Chrome or Firefox
I use this script to validate file type and size
var _validFilejpeg = [".jpeg", ".jpg", ".bmp", ".pdf"];
function validateForSize(oInput, minSize, maxSizejpeg) {
//if there is a need of specifying any other type, just add that particular type in var _validFilejpeg
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFilejpeg.length; j++) {
var sCurExtension = _validFilejpeg[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length)
.toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, this file is invalid, allowed extension is: " + _validFilejpeg.join(", "));
oInput.value = "";
return false;
}
}
}
fileSizeValidatejpeg(oInput, minSize, maxSizejpeg);
}
function fileSizeValidatejpeg(fdata, minSize, maxSizejpeg) {
if (fdata.files && fdata.files[0]) {
var fsize = fdata.files[0].size /1024; //The files property of an input element returns a FileList. fdata is an input element,fdata.files[0] returns a File object at the index 0.
//alert(fsize)
if (fsize > maxSizejpeg || fsize < minSize) {
alert('This file size is: ' + fsize.toFixed(2) +
"KB. Files should be in " + (minSize) + " to " + (maxSizejpeg) + " KB ");
fdata.value = ""; //so that the file name is not displayed on the side of the choose file button
return false;
} else {
console.log("");
}
}
}
<input type="file" onchange="validateForSize(this,10,5000);" >
If you set the Ie 'Document Mode' to 'Standards' you can use the simple javascript 'size' method to get the uploaded file's size.
Set the Ie 'Document Mode' to 'Standards':
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
Than, use the 'size' javascript method to get the uploaded file's size:
<script type="text/javascript">
var uploadedFile = document.getElementById('imageUpload');
var fileSize = uploadedFile.files[0].size;
alert(fileSize);
</script>
It works for me.
Simple way is
const myFile = document.getElementById("fileUpload").files[0];
if (myFIle.size > 2097152) // 2 MiB for bytes.
{
alert("File size must under 2MiB!");
return;
}

How optimal the code can be with dynamically adding the controls

In a website I am designing I need to show images which I upload using asp:FileUpload control. So after uploading I am adding div, img and textarea using a string builder and then loading it into panel which I have already created. So is it better to use Stringbuilder to load inner HTML or is it good to use HtmlgenericControls to add the controls like image and textarea. I am using C#. My current coding way is as follows:
Frontend:
<form id="form1" runat="server">
<div class="transbox" id="mainbk" runat="server" style="position:absolute; top:0px; left:0px; width: 100%; height: 100%;" >
<asp:FileUpload runat="server" ID="UploadImages" style="background-color:white; position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 350px; right: 251px;" Width="500px" AllowMultiple="true"/>
<asp:Button runat="server" ID="uploadedFile" style="position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 870px; width: 112px; height: 29px;" Text="Upload" OnClick="uploadFile_Click" />
<asp:Panel ID="updtpanel" runat="server" CssClass="transbox" style="width:100%;height:100%;left:0px;top:0px;position:absolute" Visible="false">
</asp:Panel>
</div>
</form>
and backend is as follows:
protected void uploadFile_Click(object sender, EventArgs e)
{
if (UploadImages.HasFiles)
{
int tid = 0;
string fileExt = Path.GetExtension(UploadImages.FileName).ToLower();
if (fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".jpg" || fileExt == ".bmp")
{
HtmlGenericControl d = new HtmlGenericControl("div");
Button btnsave = new Button();
btnsave.Text = "Save";
sb.Append("<div class=" + "\"savback\"" + ">");
sb.Append("<div class=" + "\"head\"" + ">Write Description</div>");
foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
{
id += 1;
tid = tid + 1;
string textid = "txt" + tid;
filepath = Server.MapPath("~/Images/Gallery/" + uploadedFile.FileName);
uploadedFile.SaveAs(filepath);
newpath = "../Images/Gallery/" + uploadedFile.FileName;
try
{
updtpanel.Visible = true;
sb.Append("<div class=" + "\"dataload\"" + ">");
sb.Append("<img class=" + "\"loadimg\"" + "src=" + "\"" + newpath.ToString() + "\"" + " />");
sb.Append("<textarea class=" + "\"txtdes\"" + "id=" + "\"" + textid + "\"" + "></textarea>");
sb.Append("</div>");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
sb.Append("</div>");
d.InnerHtml = sb.ToString();
updtpanel.Controls.Add(d);
updtpanel.Controls.Add(btnsave);
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select only Image Files!!');", true);
}
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select a File First!!');", true);
}
}
Please let me know which will be the good way of creating dynamic controls??
Optimal code:
Doesn't contain more than 50 lines of difficult to read code (agreed, it's not unreadable, but still, minor refactoring would help),
Doesn't mix CSS with HTML, together with presentation-related HTML attributes such as width,
Doesn't use the JavaScript alert.
Let's get back to your question. Which one is better: StringBuilder or HtmlGenericControl?
Better being an extremely vague term, let's answer a bunch of slightly different questions:
Which one is faster ?
Probably StringBuilder, given that it doesn't matter. At all. Compared to the time spent downloading an image (say two seconds, i.e. 2 000 ms.), the comparison in performance between StringBuilder and HtmlGenericControl will be very probably less than a millisecond. Is it important that you waste 1 ms. on a process which takes 2 000 ms.?
Which one is safer ?
How many errors do you spot in the following code?
sb.Append("<div class=\"illustration\"><span-class=\"contents\">")
.Append("<img class=" + "\"loadimg\"" + "srv=" + "\"" + newpath + "\"" + ">")
.Append("/div></span>");
Let's see:
div and span are inverted,
the closing div is missing the '<' character,
img is missing '/' (if the output is XHTML),
there is a typo in src written as srv,
span-class should have been span class,
there is no space before src (srv).
Nearly every of those mistakes could have been easily avoided by letting .NET Framework the task of generating HTML from strongly typed objects.
Which one is more readable ?
IMO, neither. HTML code can be written in a clean way, making it extremely readable. In the same way, it would be easy to be lost in all those calls to embedded controls if the code is a piece of crap.
Which one is more reliable ?
.NET Framework is assumed to be heavily tested and particularly reliable, at least compared to average business applications. The more you confide to .NET Framework, the better, unless you know how to do better and you've tested your approach, submitted it for pair reviews, etc.
In the case of StringBuilder, you can hardly unit-test your code. Letting .NET Framework do the HTML generation in your place means that you can concentrate more on the actual objects you manipulate, and testing them is slightly easier.
So, what is the single best solution ?
Personally, if I were stick with classical ASP.NET (by contrast to ASP.NET MVC), I would create a dedicated control with an HTML template.
If for some reasons, this is not possible, then pick HtmlGenericControl: it abstracts the HTML and let you concentrate on the objects themselves.
If you had a requirement to write clean, readable HTML code, HtmlGenericControl would be a burden, and you would have to pick string concatenation or some templating system. ASP.NET controls are known for generating not-so-good HTML code. Given the HTML code in your question, this limitation doesn't apply to your case.

Sending querystring variable to new popup window

My JavaScript code is this:
var newwindow;
function poptastic(url) {
newwindow = window.open(url, 'name', 'height=400,width=200');
if (window.focus) { newwindow.focus() }
}
And my C# code:
foreach (GridViewRow row in GvComments.Rows)
{
Button btnReplay = (Button)row.FindControl("btnReplay");
string url = "javascript:poptastic('Configuration.aspx?id=" + e.CommandArgument + "')";
btnReplay.Attributes.Add("onclick", url);
}
I think the C# code has problem, because when I use this JavaScript code in a tag it works, but in attribute.add not working.
Try using OnClientClick for this instead:
btnReplay.OnClientClick = String.Format("poptastic(\"Configuration.aspx?id={0}\");return false;", e.CommandArgument);
EDIT
Here's a JavaScript function you can use to open popup windows:
openChildWindowWithDimensions = function(url, width, height, showMenu, canResize, showScrollbars) {
var childWindow = window.open(url, "", "\"width=" + width + ",height=" + height + ",menubar=" + (showMenu ? "1" : "0") + ",scrollbars=" + (showScrollbars ? "1" : "0") + ",resizable=" + (canResize ? "1" : "0") + "\"");
if (childWindow){
childWindow.resizeTo(width, height);
childWindow.focus();
}
}
This problem would be very easy to answer, if you can provide the HTML generated. To find HTML generated go the browser window where you are seeing the rendered page and do a View Source. See How do I check my site's source code
With the code you have provided all the suggestions I can make are already made by #James Johnson
Please see a minor correction to James code
btnReplay.OnClientClick = String.Format("poptastic('Configuration.aspx?id={0}');return false;", e.CommandArgument);
Note: I have changed \" to '

Categories

Resources