I'm using the ASP.NET FileUpload control.
To upload a file, a user must:
Browse to select a file from his/her device,
Click the upload button to upload the file to the server.
Is it possible to skip step 2 (the Upload button) and call the 'uploadFile_Click' function on the server through a jquery (postback) once a file is selected? I'm trying the following method but I need some help to finalize it.
ASPX PAGE
<asp:FileUpload runat="server" ID="UploadImages" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="UploadImages" ClientValidationFunction="ValidateUpload" />
CODE BEHIND
protected void uploadFile_Click(object sender, EventArgs e)
{
// Upload code
}
JQUERY
function ValidateUpload() {
var FileUpload_function = document.getElementById('UploadImages');
if (FileUpload_function.value == '') {
return false;
}
else {
** Here I want to trigger a postback to call the uploadFile_Click. Is that possible? **
}
return true;
}
Some (most?) browsers will not allow you to call the click event on an input HTML element if it is of type file (ie. an asp:fileupload control). It is considered a security risk.
Related
When user will click on button, I want to open one .aspx/.html page in different tab and open one .aspx/.html page in same tab.
Sample code:
string redirect = "<script>window.open('../User/Profile.html');</script>";
Response.Write(redirect);
Response.Redirect("../User/NewUser.aspx",true);
Thanks in Adance!!!
No, the response redirect writes in the http's header the "location" value and can only have one, but you can write a javascript like the next for do what you need:
window.open('../User/Profile.html', 'tabName');
window.location.href = '../User/NewUser.aspx';
Good luck!
We can achieve by using Javascript and code behind page
Call Javascript Window.Open() function on Clientclick property to open in new window.
and onClick call your code behine buttonClick Event to redirect on same window.
ASPX Page:
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" OnClientClick="javascript:window.open('http://google.com','_blank');return true;" />
Code behind On Click function:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("http://google.com");
}
This code not working on Chrome :
window.location.href = '../User/NewUser.aspx';
But you can use this code instead of window.location.href then its working in all browsers :
setTimeout(function(){document.location.href = "page.html"},500);
So I'm creating a dummy webpage for basics right now. The Goal:
On a button click, I want to update information shown in the textbox.
The method myButton_Click takes in the parameters of the button. How can I access an object like textbox (or any object for that matter) since it is not being accessed from a buttonclick event? I set up a public variable, myTextBox_, which I think I could then edit freely. But I'm still not sure how to set myTextBox_ to understand that it is connected to the webpage.
Html:
<form id="form1" runat="server">
<p style="height: 324px">
<asp:Button ID="myButton" runat="server" EnableTheming="True" Text="Button" onclick="myButton_Click"/>
<asp:TextBox ID="myTextBox" runat="server">Hello</asp:TextBox>
</p>
</form>
Then the C# Code:
Textbox myTextBox_;
protected void Page_Load(object sender, EventArgs e)
{
//possibly initialization code set myTextBox_ to the id myTextbox, but how?
}
protected void myButton_Click(object sender, EventArgs e)
{
myTextbox_.text = "goodbye";
}
You're very close. All you need to do is:
protected void myButton_Click(object sender, EventArgs e)
{
myTextBox.Text = "goodbye";
}
You don't need to set up anything in the Page_Load method, as you have them set up as runatserver, so they are accessible from the code behind.
As already stated, this will require a postback to work, to avoid this use AJAX or do it in pure JavaScript.
If you want to learn web on .NET, you should start learning ASP.NET MVC, not web pages.
Anyhow, I believe you don't get the same behaviour as in a desktop app, because when you click the button, you get a page postback (whole page is refreshed). You should use the page's postback event to change the text, not the button.
Or you should use the old "UpdatePanel" from ASP.NET Ajax 1.0, to put the button and the textbox in the same UpdatePanel (but you must first install that ASP.NET Ajax 1.0)
But pls, start using MVC :)
http://www.asp.net/mvc
I have got a checkbox and want to display the confirmation message when it is clicked
I added the event binding in Code Behind file as below.
chkSMTLock.Attributes.Add("onclick", "return ConfirmSMTLock();");
The following is my HTML code for chkSMTLock
<asp:CheckBox ID="chkSMTLock" runat="server" AutoPostBack="true" OnCheckedChanged="chkSMTLock_CheckedChanged" Text="SMT Lock" />
Here is my javascript:
function ConfirmSMTLock() {
var r = confirm('Are you sure that you want to SMT lock/unlock this account?');
console.log(r);
return r;
}
When I run it, I can see the confirmation values (true/ false) in the browser console logs, but, it's not calling any server side code.
My server side code is very simple with logging...
protected void chkSMTLock_CheckedChanged(object sender, EventArgs e)
{
Utils.Debug("chkSMTLock_CheckedChanged");
}
When I remove javascript event binding for the checkbox, it executes the ServerSide event successfully. But When I put it back, it stops working.
How can I use the confirmation message box to control it?
Your validation is too far down the chain. As you've got AutoPostBack=true, you're basically submitting a form when clicking the checkbox, your validation wants to be at the form level.
Form.Attributes.Add("onclick", "return ConfirmSMTLock();");
And in ConfirmSMTLock() check the status of the checkbox to see if you need to fire the confirm dialogue. That's the simplest way I can think of.
On a side note: if you do this:
chkSMTLock.Attributes.Add("onclick", "return false;");
The checkbox becomes untickable
I have found out an answer. Since AutoPostBack = true, it will automatically send a post back to the server. So, first you need to delete that attribute from the html code.
<asp:CheckBox ID="chkSMTLock" runat="server" OnCheckedChanged="chkSMTLock_CheckedChanged" Text="SMT Lock" />
Then implement the PostBack behaviour by using the __doPostBack function of ASP.Net.
function ConfirmSMTLock() {
var r = confirm('Are you sure that you want to SMT lock/unlock this account?');
if (r == true)
{
__doPostBack("chkSMTLock", '');
return true;
}
return false;
}
Open Sasame!!!
I have an asp:GridView control inside a .aspx page that the user can add several rows of data to. The user must also be able to attach a file to each row of data added.
For this I use the following inside the GridView:
<asp:TemplateField HeaderText="Upload" HeaderStyle-Width="120px">
<EditItemTemplate>
<asp:FileUpload ID="fuUploadLocation" runat="server" Width="98%" TabIndex="18" />
</EditItemTemplate>
</asp:TemplateField>
Then to save the location of the file upload I use the RowUpdating event in code-behind to set the value etc.
The problem is I can't register a PostBackTrigger for the control on the html as it doesn't pick it up as it's inside the GridView. I've tried setting it dynamically from other examples but can't seem to get this to work, the result being my FileUpload's FileName is always empty and the file then doesn't save correctly.
Any suggestions would be awesome.
Thanks
On Gridview row databound you have to find the file upload control and then add it to your UpdatePanel postback trigger.
I've not found a solution to my problem but I did work around it (sort of). I know just add a link to the grid, when user clicks it sends ID through via querystring, a new page opens that handles the entire upload process and returns the url of the saved document.
Not ideal but it works and saved me hours of frustration.
In the OnItemDataBound event handler of the grid need to call ScriptManager.GetCurrent(this).RegisterPostBackControl(ControlID);
This is an old post but for anyone that is stuck with it, you need to add the following to your control as stated in the other answers.
protected void ItemDataBound(object sender, EventArgs e)
{
Button myButton = (Button)e.Item.FindControl("myButton");
if (myButton != null)
ScriptManager.GetCurrent(Page).RegisterPostBackControl(myButton);
}
You also need to change the enctype in your form tag to the following e.g.:
protected void Page_PreRender(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
}
It should then work without an issue.
For my internal webpage at work, I display a DataGrid based on entries in a SQL table (not directly, but with some processing on entries).
Each row in the DataGrid has a button that the user clicks. I need this button to open a new window or tab (I believe I can't decide as this is based on browser config) and also change a value in the SQL table to say the button was clicked.
If I use an asp:Hyperlink then the page opens nicely, but I don't know how to update SQL. Vice-versa if I use an asp:LinkButton I can get the SQL updated but can't get a new page to open.
Is what I am trying to do impossible?
Thanks
EDIT:
I've tried both these in my .cs file, but neither worked:
ClientScript.RegisterStartupScript(GetType(), "openwindow", "window.open('" + url + "','_preview'");
Response.Write("<script type='text/javascript'>detailedresults=window.open('" + url + "');</script>");
<asp:TemplateField HeaderText="Action"> <ItemTemplate>
<asp:LinkButton ID="lbtnConfigureSurvey" runat="server" CausesValidation="False"
CommandName="ConfigureSurvey" CommandArgument='<%# Eval("intSurveyID") %>'
OnClientClick="aspnetForm.target ='_blank';">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
protected void gvSurveyList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ConfigureSurvey")
{
Response.Redirect('Your page url');
}
}
You can use LinkButton and use OnClientClick property to set the java-script that would open the page in new browser window. This script must return true so that post-back can happen and you can handle click event on server side to update your database.
IMO, better way would be to use hyper-link and open the page in new browser window. However, you must pass a query-string parameter while opening the page (say Page2) that would tell the new page that it should update the database. So url for opening the page will be something like "page2.aspx?recordId=xyz". And within page2.aspx.cs, you will have code such as
protected void page_load(object sender, EventArgs e)
{
if (!IsPostback)
{
var recordId = Response.QueryString["recordId"];
if (!string.IsNullOrEmpty(recordId))
{
// update database
...
}
}
...
}
From security perspective, you may want to include time-out within parameter value and encrypt the entire thing.
You could use your LinkButton and call RegisterStartupScript on postback to execute something like this on page load
.aspx:
<asp:LinkButton OnClick="OnButtonClick" Text="Update" runat="server" />
.aspx.cs:
protected void OnButtonClick(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "openwindow", "<script type=text/javascript> window.open('About.aspx'); </script>");
}
You need to supply the whole script element to RegisterStartupScript.
try this
Response.Write("<script type='text/javascript'>detailedresults=window.open('PAGE NAME.aspx');</script>")
EDIT:
you can set command name for link button and execute code in rowcocommand event
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("commandname for linkbutton"))
{
//update code
Response.Write("<SCRIPT language=\"javascript\">open('Yourpage.aspx','_blank','top=0,left=0,status=yes,resizable=yes,scrollbars=yes');</script>");
}
}
Hyperlink will not call server side event on click, so you won't get post back to perform the SQL task, and by using the LinkButton you can open the page in the new window or tab. To do so you need to add a little code below in the Grid_RowBoundEvent.
Ex: LinkButton.OnClientClick="window.open('http://www.google.com');";
The url you can change as per your requirement.
Again, in the Code behind you will get a server side event. There you can do your sql task.
Hope it will be helpful to you.