I want to delete a directory when its clicked on a hyperlink.I tried like the below.But my page redirecting to default(start) page and the directory is not deleting.
protected void Page_Load(object sender, EventArgs e)
{
Execute(s,Content,k,j);
}
private void Execute(string path,string cont,string sym,string space )
{
foreach (var directory in new DirectoryInfo(path).GetDirectories())
{
string f = directory.FullName;
f = Server.UrlPathEncode(f);
Response.Write("<a href =''" + "onclick='Delete(" + f + ")'> DELETE </a>");
Execute(directory.FullName,cont1,sym1,space1);
}
}
private void Delete(string path)
{
DirectoryInfo DirDel = new DirectoryInfo(path);
DirDel.Delete();
}
Can you tell me the problem in this code?
It is not clear from your question, where you have that folder, if it is on the client side, then i think it is not possible.
If it is on the server side you could use a link button instead of an anchor tag to run the code behind function
If you cant use the link button for some reason you could use JavaScript ajax calls to call the code behind function.
Here is a code project article, that may help you
You're rendering clientside code, expecting it to call serverside code. This will never work, clientside always happens on their machine, not on your server.
What you want is to use a LinkButton control, e.g.:
<%# Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>LinkButton Example</title>
<script language="C#" runat="server">
protected void LinkButton_Click(Object sender, EventArgs e)
{
// Code to delete directory
}
</script>
</head>
<body>
<form id="form1" runat="server">
<h3>LinkButton Example</h3>
<asp:LinkButton id="LinkButton1"
Text="Click Me"
Font-Names="Verdana"
Font-Size="14pt"
OnClick="LinkButton_Click"
runat="server"/>
<br />
<asp:Label id="Label1" runat="server" />
</form>
</body>
</html>
The general problem is that you create client-side URLs, but method to call is server-side. So you need to create server-side URLs, and handle postback click:
string path = #"d:\Temp";
protected override void OnInit(EventArgs e)
{
string dir = this.Request["dir"];
if (String.IsNullOrEmpty(dir)) // write links
{
foreach (var di in new DirectoryInfo(path).EnumerateDirectories())
{
var link = new HyperLink()
{
Text = di.Name,
NavigateUrl = String.Format("?dir={0}", HttpUtility.UrlEncode(di.Name))
};
this.Controls.Add(link);
}
}
else // process link click
{
dir = HttpUtility.UrlDecode(dir);
path = Path.Combine(path, dir);
Directory.Delete(path);
Response.Redirect("~/Default.aspx"); // page's name to refresh content
}
}
You should use a LinkButton to get the same look as the , but you need your code to be execute on server side as the PostBack for your LinkButton.
The code you have here will make a call to a client-side script.
Related
During the page_load, I disable the timer. When I pressed Button1, I enable the timer, but the page refreshes. Therefore, it never reaches the timer_tick1. I need to show a popup after a certain amount of time a button is clicked. How do I prevent the refresh from happening?
Alerts Class
public static class Alert
{
public static void Show(string message, Page page)
{
// replaces the quotations to follow the script syntax
// quotations are interpretated as \\' in script code
string cleanMessage = message.Replace("'", "\\'");
string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
// Gets the executing web page
Page tempPage = page;
// Checks if the handler is a Page and that the script isn't already on the page
if (tempPage != null & !tempPage.ClientScript.IsClientScriptBlockRegistered("alert"))
{
tempPage.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script); // this isn't working, but it works on a button click event.
}
}
}
Page Class
public partial class Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback) {
Timer1.Enabled = false;
Label2.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if page reloads
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{ // i added a breakpoint here. It doesn't even pass through.
Alert.Show("hehehehe", this); //PopUp Shows up.
Timer1.Enabled = false; //Cancels Timer
Label1.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if update panel reloads
}
protected void Button1_Click1(object sender, EventArgs e)
{
Timer1.Enabled = true; //Starts Timer. It seems to refresh the page.
}
}
script
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test1.aspx.cs" Inherits="Test1" %>
<%# Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
function delayer() {
setTimeout (function () {ShowPopUp()}, 15000);
}
delayer();
</script>
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="1000" Enabled="true">
</asp:Timer>
<asp:Label ID="Label1" runat="server" Text="PanelNotRefreshedYet"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="ShowPopUp();" />
</form>
</body>
</html>
I think you're confused. Timer1 is a server side control. So it will fire on the server side, if you're still processing the page, that is, and will have no effect on the client side. By the time it fires in your code, the page has likely already rendered so you'll see no effect from that Timer1 object's Timer1_Tick event. Since the page has completed rendering, you can't inject new JavaScript, modify the page, or anything like that. Remember that web development is a disconnected thing. You send a request, you get a response. There are no events by nature of the web. There are libraries out there for triggering events and such but I think that's way beyond what you're trying to achieve.
For client side "timer" you need to use JavaScript setTimeout method, which you have verified as working and is the proper way for you to achieve the delay you're looking to implement.
setTimeout (function () {ShowPopUp()}, 15000);
If you still want to do it in your Alert class, then get rid of Timer1 and have your Alert class inject the timeout in JavaScript:
protected void Button1_Click1(object sender, EventArgs e)
{
Alert.Show("He heee", this);
}
And in Alert, change your script to:
string script = "<script type=\"text/javascript\">setTimeout(function() {alert('" + cleanMessage + "');}, 15000);</script>";
Your button is doing a postback, so yes the page will be refreshed and your Page_Load function will run again. You should test for this using the IsPostback property.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback) {
Timer1.Enabled = false;
Label2.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if page reloads
}
}
You might want to look at showing the alert using JavaScript on the page rather than running it server side tho.
<script type="text/javascript">
function showPopup()
{
alert("Hey, click something already");
}
function delayer() {
setTimeout (showPopUp, 15000);
}
delayer();
</script>
Just put your message like this. Probably easier if your logic is simple.
I am posting this question again, maybe this time more accurate description.
The problem is , I am using jQuery to set the Label's text value and it works fine on browser, but when I want to save it to string, it does not save it. Here is the
front End Html Code.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(window).load(function () {
var myNewName = "Ronaldo";
$('#<%= Label1.ClientID %>').text(myNewName);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
And here is the Back End C# Code On Page Load
using System;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
}
The result displayed is
Name's not Fine
Ronaldo
Seems like the string is still Null. Is there any problem of rendering??
label is not input type so you can not get changed values through jquery on server side. You can use hidden field for this purpose.
Your server side code (c#) can not access the form data until your client side code (HTML/Javascript) posts it.
Why do you want to the name already at the PageLoad event?
You could add a asp:Button with an attached onClick event handler to read the value of your asp:Label.
Labels do not maintain viewstate. The server will not post that information back to the server. You can try explicitly enabling the ViewState on your Label, but if that doesn't work, you will have to store that value in a hidden field.
First Call Page Load event and after that call JQuery Window.Load event.
So if you want to set any content in Label then you can do using onClientClick of button.
For ex.
<asp:Button ID="btn" runat="server" Text="Click me" OnClientClick="SetClientValues();" />
<script type="text/javascript">
function SetClientValues() {
var myNewName = "Ronaldo";
$('#<%= Label1.ClientID %>').text(myNewName);
}
</script>
At server side button event you can get Label values that sets at client side.
protected void btn_Click(object sender, EventArgs e)
{
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
It will print Yes Name is Fine
This should do it:
<script type="text/javascript">
$(window).load(function () {
if($('#<%= Txt1.ClientID %>').val() != "Ronaldo"){
var myNewName = "Ronaldo";
$('#<%= Txt1.ClientID %>').val(myNewName);
$('#<%= Label1.ClientID %>').text(myNewName);
$('#<%= Btn1.ClientID %>').click();
}
});
</script>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="Txt1" runat="server" style="display:none"></asp:Label>
<asp:Button ID="Btn1" runat="server" style="display:none" Click="Btn1_Click"></asp:Label>
</form>
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
Label1.Text=Txt1.Text;
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
}
protected void Btn1_Click(object sender, EventArgs e)
{ }
Hope it helps :)
I am trying to add a few additional lines of code to the Page_Load method of an ASP.Net page, where the existing Page_Load code is stored in a compiled codebehind DLL. I don't have access to the source for the DLL, although I can extract the code for the Page_Load method using Dis#.
What is the best way to add the new code? I need the existing Page_Load code to execute, together with the new code, and it doesn't matter in what order they execute.
Specifically, I'm fixing an old application that uses the Telerik RadEditor which doesn't work correctly under Firefox 6. See this page for the exact code I'm adding.
If you can access the ASPX portion, you can try adding a code block to the ASPX, and overriding OnInit or OnPreInit, which should work fine for the code you're trying to add.
<script runat="server">
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if (Request.Browser.Browser.ToLowerInvariant() == "firefox")
{
System.Reflection.FieldInfo browserCheckedField = typeof(RadEditor).GetField("_browserCapabilitiesRetrieved", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
browserCheckedField.SetValue(RadEditor1, true);
System.Reflection.FieldInfo browserSupportedField = typeof(RadEditor).GetField("_isSupportedBrowser", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
browserSupportedField.SetValue(RadEditor1, true);
}
}
</script>
You can derive from the other Page class and add a Page.Load event handler:
public class YourPage : TheirPage
{
public YourPage() { Load += YourPage_Load; }
void YourPage_Load(object s, EventArgs e) { ... }
}
or even override OnLoad():
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
...
}
You would need to extract all source, add your code and rebuild the entire dll. There is not a way to do this without rebuilding the original assembly. This will be a problem if the original assembly is strong-named. Otherwise, it's a pain but you should be ok.
can you possibly hook into PreLoad in the aspx page? Controls are loaded at this point and you should be able to do what you need. Sometimes additional processing is required and you can hook into LoadComplete as well which I think may serve you best?
http://msdn.microsoft.com/en-us/library/system.web.ui.page.preload.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.page.onloadcomplete.aspx
If you can extract the code from the DLL by dissasembling it, you can disassociate the code behind the page and reimplement the logic in the markup.
<%# Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
lblTest.Text = "Something here";
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblTest" runat="server" ></asp:Label>
</div>
</form>
</body>
</html>
You can derive from the existing class and override any of the rendering methods, such as the OnPreRender() method:
public class Class1 : _Default
{
protected override void OnPreRenderComplete(EventArgs e)
{
base.OnPreRenderComplete(e);
// add your code here
}
}
i am trying to use javascript events in asp.net webforms. but events for input controls like textfield, such as onClick, onFocus,onBlur, dont appear. do i need to change my directive:
<%# Page Title="" Language="C#" MasterPageFile="~/YourGuruMaster.master" AutoEventWireup="true" CodeFile="AskQuestion.aspx.cs" Inherits="AskQuestion" %>
i want to be able to do this:
//code page
protected void Page_Load(object sender, EventArgs e)
{
QuestionTextBox1.Attributes["onfocus"] = "ClearSearchText()";
//Markup page
function ClearSearchText() {
var searchUserName = document.getElementById('<%=QuestionTextBox1.ClientID%>');
if (searchUserName.value = searchUserName.defaultValue) {
searchUserName.value = "";
}
return false;
}
<p dir="rtl" style="">
<asp:TextBox ID="QuestionTextBox1" runat="server" Width="702px"
Text="פרטים עד 5000 תווים"></asp:TextBox>
Add onfocus and onblur into the markup as follows:
<asp:TextBox ID="TextBox1" runat="server" onfocus="TextBox1_focus(this, event)" onblur="TextBox1_blur(this, event)" Text="Search..."></asp:TextBox>
<script type="text/javascript">
var searchText = 'Search...';
function TextBox1_focus(sender, e) {
if (sender.value == searchText)
sender.value = '';
}
function TextBox1_blur(sender, e) {
if (sender.value == '')
sender.value = searchText;
}
</script>
Well, not sure which ASP.NET version you use. I think last versions allow this (rendering attributes that the server controls don't understand to the browser still). Try using "onfocus" instead (lower case).
However, if this is not working for you, then you have to do it from code behind...
protected void Page_Load(object sender, EventArgs e)
{
QuestionTextBox1. Attributes["onfocus"]="someJavaScriptMethod";
}
Alternatively, if you have jQuery in the page you can go something like ...
<script type="text/javascript">
$(function() {
$('#<%= QuestionTextBox1.ClientID %>').focus(someJavaScriptMethod);
});
</script>
If you do that, inside someJavaScriptMethod(), you can use the word this to point at the focused control, and you can create a jQuery object from it easily like $(this).
.
Please leave me a comment if none of the above solves your problem.
i"m using asp.net FileUpload , after user input file he click on save button
in the c# i have this function
protected void btnUploadImages_Click(object sender, EventArgs e)
{
SaveImages(FileUpload1, "", returnAlbumId, out returnPhotoId);
}
this function save the image from the FileUpload1 so far all work as it"s should
but after the postback when i push the refresh button on the page i"m go to this function again , SaveImages function save the same image again .
the FileUpload1 didn't clear after the postback
thanks
Even i got the Same Problem I have resolved like Below.
After uploading the File If you Redirect to same page or some other page in your project. After Redirection Response will not be there once you redirected.
In My ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm.aspx.cs" Inherits="WebApplication.WebForm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
In My Code Behind
public partial class WebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string path = Server.MapPath("~");
path = path + FileUpload1.FileName;
FileUpload1.SaveAs(path);
Response.Redirect("WebForm.aspx"); // Responce will be cleared. This Redirection will do the Trick
//Put the debugger and check it will work
}
}
Here, to show the success and error messages try to use sessions.