I have a asp file upload for pictures and what I want to do is, when the file chosen has the same name as the previous file it should pop something up that says "This image name already exists, do you want to replace it? if yes then it would just override the current picture with the new one but if not then just leave it alone. How can I do this?. Right now I have this. Also if the solution is in javascript I could also use that (but i am not too good with javascript :) ) Thank you
<div class="style">
Choose an Image: <asp:FileUpload ID="getImage" runat="server" Width="150px" BorderStyle="Inset" EnableViewState="true" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator"
runat="server" ControlToValidate="getImage" CssClass="Error" Display="dynamic" ValidationExpression=".*(\.[Jj][Pp][Gg]|\.[Gg][Ii][Ff]|\.[Jj][Pp][Ee][Gg]|\.[Pp][Nn][Gg])" ErrorMessage="Select a correct file format"></asp:RegularExpressionValidator>
</div>
Please be aware I am a total newbie with Javascript so if that is what's going to work please explain as if I was a 5 year old.
I really appreciate the help.
My solution will perform the check just before postback. I also use jquery a little bit.
The important piece of the puzzle here is retrieving the previous file name. I created a PageMethod to do this part. So in my aspx.cs file I have a function that looks like this:
using System.Web.Services;
.......
[WebMethod()]
public static string GetPreviousFileName()
{
//put logic here to get the filename to compare against.
return "somefilename.ext";
}
You'll need to implement your own logic for how to retrieve the file name. Another, simpler but less flexible, approach for handling the previous file name would be to add an asp:hiddenfield to your page and populate it with the name of the previous file on page load. Then you could compare by reading $('#<%= hiddenField.ClientID %>').val().
Next I used the following code for my file upload control and a submit buton:
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" />
<div>
<asp:FileUpload ID="fu" runat="server" />
<asp:Button ID="btnUpload" runat="server" OnClientClick="return checkDuplicateFile();" Text="Upload File" />
</div>
Two important things to note here: The ScriptManager has EnablePageMethods="true" and the asp:button has an OnClientClick attribute specified. Lastly, the javascript part of the solution which retrieves the value from the page method and and compares the file names:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var oFilename = "";
$(function () {
//get original file name on page load
PageMethods.GetPreviousFileName(function (result) {
oFilename = result;
});
});
function checkDuplicateFile() {
var newVal = $('#<%=fu.ClientID %>').val();
var newValFile = newVal.substr(newVal.lastIndexOf("\\") + 1);
//returning true causes postback, returning false stops postback.
if (newValFile == oFilename) { return confirm("This image name already exists, do you want to replace it?"); }
else return true;
}
</script>
Couple of things going on here. We use our pagemethod to pull in our old filename from the page method on page load (PageMethods.GetPreviousFileName). Next we setup the function which will be called by our buttons onClick event (client side). The <%=fu.ClientID %> snippet of code will output the client side id of the file upload control for use in our javascript. I do a substring on the file path and extract the file name by pulling back only the text after the last '\' and do the compare.
As my comment in the function says, returning true/false from a function called in the OnClientclick event determines whether a post back occurs. So if the user clicks yes in the confirmation box then a postback occurs, else if they click no then none occurs.
Hope that at least gets you going in the right direction.
Add the code below to your submit button
OnClientClick="return confirm('Are you sure you want to delete this file?')"
Edit as someone pointed out this will ask this question without taking in concern previous file and new one. It will do basic job.
My question is whether you doing this for edit mode or in new item mode. I mean are you editing item or adding new one on page you are interested to check?
Related
I am trying to post back on a button click.But unable to get __EVENTTARGET and __EVENTARGUMENT. It is currently always null. Is there any other entries I have to do?
aspx
<asp:Button ID="btn" runat="server" OnClientClick="GetDet();" Text="Click"/>
<script type="text/jscript">
function GetDet() {
var obj = $('.output');
var sign = $('.name'); //hidden field
__doPostBack('btn', sign.val());
}
</script>
.cs
string tar = Convert.ToString(Request.Params.Get("__EVENTTARGET"));
string val = Convert.ToString(Request.Params.Get("__EVENTARGUMENT"));
Instead of doing such a hack. I'd actually recommend you to do things the proper way so you can guarantee scalability because you never know what's gonna happen on the next release of ASP.NET and the ASP.NET Team certainly does not endorse these types of hacks, in other words, your hacks might break with a future releases of ASP.NET...always strive to avoid them. So, if you want to do a full postback you definitely don't need javascript for this....
<asp:Button ID="btn" runat="server" Text="Click"/>
Then, if you want to post the value of the hidden field simply add the hidden field to the form...
<asp:HiddenField ID="hdfName" runat="server" Value="whatever" />
if you want to read the value of the hidden field during the postback...
public override void OnLoad(EventArgs args)
{
var name = hdfName.Value;
}
That's how you are supposed to work with ASP.NET the proper way rather than trying to hack its intrinsics
I'm trying to determine why my validation function is not being called on my web form. I've read through various articles at MSDN and most notably found this nugget.
When you use the CustomValidator control inside an UpdatePanel control,
make sure that the validator control and the control it is associated with
are in the same panel. For more information about using the UpdatePanel
control for partial-page updates, see Partial-Page Rendering Overview.
With this knowledge I modified my code as follows:
<asp:UpdatePanel ID="UpdatePanel0" runat="server">
<ContentTemplate>
<script type="text/javascript">
function IsNotChecked(obj, args) {
args.IsValid = false;
if (document.getElementByID("cbRegion0").checked)
{
args.IsValid = true; return true;
}
return false;
}
</script>
<asp:CheckBox ID="cbRegion0" runat="server" ValidationGroup="0" AutoPostBack="true" OnCheckedChanged="CheckBox_CheckedChanged" />
<asp:CustomValidator ID="CustomValidator0" runat="server" ValidationGroup="0" ClientValidationFunction="IsNotChecked" ErrorMessage="You did not check the box." ValidateEmptyText="True" />
</ContentTemplate>
</asp:UpdatePanel>
The issue I'm having is that the validation routine does not get executed when clicking the submit button on my page.
Some unique elements of the design is that the code above is actually inside of a .ascx that is added to the page via Control.Add() but I don't see how that would affect the ClientValidationFunction. I believe it's related to the placement of the <script> inside the form but despite following directions at MSDN it doesn't seem to have made a difference.
Thanks for any ideas!
Scripts inside of an UpdatePanel will be lost after an async postback. Try putting your IsNotChecked method outside of any update panels... or, implement IScriptControl and put your validation method in the client script file you create to accompany your script control...
I found the answer here at Stack Overflow in the How do I get Client-side validation of ASP.Net page to run? discussion. Sorry for not seeing this earlier. As #Brian pointed out, by specifying the ValidationGroup="0" in my code that it was expected that the submit button on the page have the same ValidationGroup assigned. In the end I just removed the attribute from the directive and it now calls the JS.
I found the answer because I was looking through the page source and noticed that the submit button was calling a javascript WebForm_OnSubmit() method which ultimately was checking Page_ValidationActive.
This led me to the question I've linked.
I hope this helps someone else.
Thanks!
I have a file upload Control and I have made this invisible.
I want to enable a browse Button for that file upload control when I click another Button.
How can I do it?
First make a file up loader like this one
To upload a file you need to do 2 things
1) Select the file. (click browse button)
2) Send it to server. (click the upload button)
So first lets write a java-script to do these.`
<script type="text/javascript" >
function uploadImage() {
$('#MainContent_UploadButton').click()
}
function selectFile() {
$('#MainContent_FileUploadControl').click();
}
</script>
Now make the file upload controller upload itself as soon as a file is selected
<asp:FileUpload id="MainContent_FileUploadControl" runat="server"
onChange="uploadImage()" class="hidden"/>
Then make a new button and let it select the file as soon as it is clicked.
<asp:Button ID="MainContent_UploadButton" runat="server" Text="Upload File"
OnClientClick="selectFile(); return false;" />
The most important point is put "return false" in the onClientClick field. It will block the buttons post back and let you choose a file without refreshing the page.
Now hide the unwanted components using css and you are done !!
I think this is not possible. This would likely be a security issue if a script could upload (or at least trigger the upload process) invisible from any user interaction.
Update:
Seems that someone actually developed a solution to hide the upload control. From what I read it seems to take some effort to develop and uses JavaScript.
Personally, I wouldn't dare to guarantee that this works on all platforms (just imagine someone with a BlackBerry or Windows Phone visits your website...) and thus avoid it.
<asp:FileUpload ID="FileUpload1" runat="server" style="display:none;"/>
<input id="btnFileUpload" type="button" value="Add" runat="server" />
btnFileUpload.Attributes.Add("onclick", "document.getElementById('" + FileUpload1.ClientID + "').click();");
I have a csv importroutine which imports my CSV values into Sitecore. After this proces is done i want to show the errors in an asp:literal. This is not working, and I think this is because i need an updatepanel for this in order to be able to update text after the first postback (the csv upload / import).
I made this:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
and coded this:
string melding = string.Format("Er zijn {0} objecten geïmporteerd.{1}", nrOfItemsImported, errors);
ViewState["Melding"] = melding;
And i have a button. On the onclick of this button I have:
Literal literal = new Literal();
literal.Text = (string)ViewState["Melding"];
literal.ID = DateTime.Now.Ticks.ToString();
UpdatePanel1.ContentTemplateContainer.Controls.Add(literal);
PlaceHolder1.Controls.Add(literal);
When i now press the button i want to update the panel so that it will show my Literal with the errormsg on it. This however isn't happening. How can this be? I'm guessing it has something to do with my viewstate, i don't see keys on the viewstate after I press the button...
#Update:
I found the problem. I was storing information in a session, however the data for the key i was storing the information in was too large. This made the Session key empty. I was posting an empty string into my literal and therefore no information was shown. I am now looking for a better way to store my data and make it show in my updatepanel. I have tried Viewstate / Session / Cookies and none of it would work the way i wanted. When I am using a viewstate I am not able to store information. The viewstate (debugmode) shows count 0 and 0 keys ... Hope someone knows a good way to make sure that my errorstring (476kb) gets stored somewhere where i can easily post it to my updatepanel's literal.
If you are using a FileUpload control, then you cannot use the UpdatePanel to asynchronously update the panel. The file upload is a synchronous event, so you'll need to update the Literal control on the page after the upload completed during the next Page_Load event.
In your code, have you tried UpdatePanel1.Update();? Even though you have added a control, you still will need to "trigger" the update to the update panel.
See here for a possible similar issue: StackOverflow
I tried this code and on click of button I am able to get the literal text on web page. Can you provide with some more details .
I am developing a user control (ascx) in ASP.NET which uses javascript for manipulating controls. Currently the javascript code is inlined and uses <%= somecontrol.ClientID %> to get the control it needs.
I want to put the javascript file in external file but from external file I cannot use the above syntax for retrieving controls. I have read about possible solutions in this and this answers but the problem is that the user control can be placed multiple times on page. This means that the Controls array (mentioned in the answers) will be rendered several times with different items. As a result the script will not be able to retrieve the id it needs. If I put <%= ClientId %> in the name of array that holds items then I will have the same problem as I am trying to solve.
Any ideas?
Ok, a different approach, that I try to use a JavaScript-class style, and then initialize it for each control.
In the external javascript file, write your code as:
function oNameCls(ControlId1) {
this.ControlId1 = ControlId1;
this.DoYourWork1 = function() {
// use the control id.
// this.ControlId1
}
this.DoYourWork2 = function() {
// use the control id.
// this.ControlId1
}
}
And on the control do the call like that.
<script language="Javascript" type="text/javascript">
// init - create
var <%=this.ClientID%>MyCls = new oNameCls(<%=Control1.ClientID%>);
// do your work
<%=this.ClientID%>MyCls.DoYourWork1();
</script>
Hope now help better.
The way I solve this problem is to use CSS classes or place the controls within containers with known IDs and then traverse into the container's children to get the actual controls. For example:
<asp:TextBox ID="Something" runat="server" CssClass="mycontrol" ... />
Could be accessed via:
jQuery('.mycontrol');
Or:
<div id="ControlContainer">
<asp:TextBox ID="Something" runat="server" ... />
</div>
Could be accessed via:
jQuery("#ControlContainer input[type='text']");
The only real problem with this approach is you're tying your code to specific markup on the page, which can be a hassle if the markup changes a lot.
What about a hidden variable:
<input type="hidden" id="ClientId" value="<%=ClientId %>">
Then from your js:
$("#" + $("#ClientID").val())
Or, put the hash in:
<input type="hidden" id="ClientId" value="#<%=ClientId %>">
...
$($("#ClientID").val())
If you want to find a specific control when there could be multiple copies, this can't be done. How would the external javascript know which of the n controls you wanted?
How can rig the behavior up to a class and find the elements relative to the position of the action control, like this:
UserControl:
<div class="myControl">
<asp:Button id="MyButton" runat="server" Text="Click Me" />
<div style="display:none;">Show me!</div>
</div>
If you jQuery was written to be relative like this:
$(".myControl input").click(function() {
$(this).next().slideDown();
});
In this case, it doesn't matter what the specific IDs are, as long as you can navigate the DOM relatively to the controls you need. Even if it's more complex like .closest("div").next().find(".bob").prev()...whatever you need to get there works.