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.
Related
I am a using ASP.NET controller to display user detail. When RadWindow is open & I tried to close with Close button. But the problem is that after page load and post back it opens again and again. I've multi-option on page: new, save, print etc. search.
<telerik:RadWindow ID="rwReport" runat="server" Behaviors="Close" KeepInScreenBounds="true"
AutoSize="true" VisibleOnPageLoad="false" Modal="true" Title="Report ACMI Advance Payment"
DestroyOnClose="true">
<ContentTemplate>
<ucRPV:ReportViewer id="ucReportViewer" runat="server" />
</ContentTemplate>
</telerik:RadWindow>
cs file code
private void Print()
{
try
{
// this.sADPs.DisplayReport();
Hashtable reportParameters = new Hashtable();
reportParameters.Add("DataSourceName", "dsACMIAdvancePayment");
reportParameters.Add("reportName", "rptACMIAdvancePayment.rdlc");
reportParameters.Add("Id", this.hfId.Value.ToString().ConvertTo<long>());
this.ucReportViewer.clearReport();
this.ucReportViewer.showReport(reportParameters);
this.rwReport.VisibleOnPageLoad = true;
//showReport(reportParameters);
}
catch(Exception e)
{
throw e;
}
}
ASPX code:
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AjaxControlToolkit" %>
<%# Register Src="../Reports/rpvReportViewerPopup.ascx" TagName="ReportViewer" TagPrefix="ucRPV" %>
<%# Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<%# Register Src="../Common/UserControls/ToolBarActions.ascx" TagName="ToolBarActions" TagPrefix="ucTBA" %>
</td>
Do not use the VisibleOnPageLoad property to show a RadWindow, register a script that will call its show() method. Thus, subsequent postbacks will not cause it to show up by itself: http://www.telerik.com/help/aspnet-ajax/window-troubleshooting-opening-from-server.html.
Of course, preventing the form from re-submitting as Felice suggested is another thing that may also be needed.
To translate this into code:
instead of:
this.rwReport.VisibleOnPageLoad = true;
use:
string script = "function f(){$find(\"" + rwReport.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
You can try below code : this might help-
<telerik:RadScriptBlock runat="server" ID="scriptBlock">
<script type="text/javascript">
//<![CDATA[
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
function CloseWin() {
//Get the RadWindow
var oWindow = GetRadWindow();
//Call its Close() method
if (oWindow) {
oWindow.Close();
}
return false;
}
</script>
</telerik:RadScriptBlock>
And on Page: yourpage.aspx;... call the function onClientClick of button:
<asp:Button ID="btnClose" Text="Close" runat="server" CssClass="button" Enabled="true" OnClientClick="CloseWin();" />
I have experienced the same problem when you reload the page because the browser resend the information and the radwindow opens again. To avoid such behavior I have adopted the following solution:
Add a hidden filed to hold the client code:
<asp:HiddenField runat="server" ID="_repostcheckcode" />
Add the following code in the code page:
protected void Page_Load(object sender, EventArgs e)
{
CancelUnexpectedRePost();
}
private void CancelUnexpectedRePost()
{
string clientCode = _repostcheckcode.Value;
//Get Server Code from session (Or Empty if null)
string serverCode = Session["_repostcheckcode"] as string ?? "";
if (!IsPostBack || clientCode.Equals(serverCode))
{
//Codes are equals - The action was initiated by the user
//Save new code (Can use simple counter instead Guid)
string code = Guid.NewGuid().ToString();
_repostcheckcode.Value = code;
Session["_repostcheckcode"] = code;
}
else
{
//Unexpected action - caused by F5 (Refresh) button
Response.Redirect(Request.Url.AbsoluteUri);
}
}
The original article can be found here.
Add a Button with an OnClick handler with the following code:
protected void CloseRadWindow(object sender, EventArgs e)
{
rwReport.VisibleOnPageLoad = false;
}
I want to hide label, whenever something is typed in text box in aspx page.
I am trying something like this :
protected void txt_LastName_KeyPress(object sender, EventArgs e)
{
Label_msg.Visible = false;
}
protected void txt_LastName_KeyDown(object sender, EventArgs e)
{
Label_msg.Visible = false;
}
But it is not happening. Do I need to write something like this in focus event?
You need javascript
Here is an implementation using jQuery
<script>
$('#txt_LastName').focus(function() {
$('#Label_msg').hide();
});
$('#txt_LastName').blur(function() {
$('#Label_msg').show();
});
</script>
A plain vanilla javascript solution would be
<script>
document.getElementById("txt_LastName").onfocus = function() {
document.getElementById("Label_msg").style.display = 'none';
};
document.getElementById("txt_LastName").onblur = function() {
document.getElementById("Label_msg").style.display = 'inherit';
};
</script>
This one may be helpful for you. Do as following...
Firstly, Set Textbox's AutoPostBack Property to true
AutoPostBack="True"
Then, Use OnTextChanged Event
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Label1.Visible = false;
}
you can do some thing simple as below:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>
<script language="javascript" type="text/javascript">
function hideOnKeyPress() {
document.getElementById('lblHidden').style.display = 'none';
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtMaintCost" onkeypress="hideOnKeyPress(); return true;" runat="server"></asp:TextBox>
<asp:Label ID="lblHidden" runat="server" Text="I'll hide when you type something in the text box" />
</div>
</form>
</body>
</html>
You can't change the visibility of a layer event based server side. You have to put this into a javascript procedure.
You have to possibilities: The easy way is, to use jQuery (you need to include jQuery!):
<script type="text/javascript">
$(function() {
$('#txt_LastName').focus(function() {
$('#Label_msg').hide();
});
$('#txt_LastName').blur(function() {
$('#Label_msg').show();
});
}
</script>
Second method: do it the hard way
If you don't want to use jQuery for some reason, you have to work directly with the DOM.
You can read about it there: W3Schools DOM Methods
You may want to look into a JavaScript MVVM library, such as KnockoutJS, like this:
<p>Your value: <input data-bind="value: someValue, valueUpdate: 'afterkeydown'" /></p>
<p>You have typed: <span data-bind="text: someValue"></span></p>
// Here's my data model
var viewModel = {
someValue: ko.observable("edit me")
};
ko.applyBindings(viewModel); // This makes Knockout get to work
Here is a jsFiddle to illustrate how easy it is to achieve your desired key down functionality with JavaScript via KnockoutJS.
a simple javascript solution would be
HTML
<span id="one">text</span>
<input type="text" onkeypress="hide()" />
Javascript
var isHidden = false;
function hide(){
if(!isHidden){
isHidden = true;
document.getElementById("one").setAttribute("style","display:none");
}
}
jsbin demo
Because there is no KeyPress Event in ASP.Net forms unlike Winforms you must use JQuery short hand code (for JavaScript) to handle hiding your label when user is typing in the textbox like this example:
<script>
$(document).ready(function () {
$("#txtUserName").keypress(function () {
$("#lblUser").hide();
});
});
</script>
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 create Div dynamically on the press of button click.
For that i refered this link>> http://forums.asp.net/t/1349244.aspx
and made code on server side(.cs page) as follows>>
public static int i = 0;
protected void Button1_Click(object sender, EventArgs e)
{
i++;
HtmlGenericControl newControl = new HtmlGenericControl("div");
newControl.ID = "NEWControl"+i;
newControl.InnerHtml = "This is a dynamically created HTML server control.";
PlaceHolder1.Controls.Add(newControl);
}
This code was giving me just one div each time when i press the button., I wanted to have addition of divs.
On client side using javascript also i tried>>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" OnClientClick="addDiv();" />
</div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</form>
</body>
</html>
<script type="text/javascript">
function addDiv() {
alert("Control comming in function");
var r = document.createElement('Div');
r.style.height = "20px";
r.style.width = "25px";
r.appendChild("div");
alert("Control going out of function");
}
</script>
Both of these didnt work.
What mistake am i making?
Is there any thing wrong?
Use this
public int Index
{
get
{
if(ViewState["Index"]==null)
{
ViewState["Index"]=0;
}
else
{
ViewState["Index"]=int.Parse(ViewState["Index"].ToString())+1;
}
return int.Parse(ViewState["Index"].ToString());
}
}
protected void Button1_Click(object sender, EventArgs e)
{
HtmlGenericControl newControl = new HtmlGenericControl("div");
newControl.ID = "NEWControl"+Index;
newControl.InnerHtml = "This is a dynamically created HTML server control.";
PlaceHolder1.Controls.Add(newControl);
}
It is giving you one div, cause you are adding one div.
Remember that asp.net needs you to create all dynamically added controls on very PostBack after that.
If you want two controls you have to add two to the PlaceHolder.
Just use one parent div with some ID(predefined lets say id="dvDynamic") and runat="server"
and then use it the dvDynamic.innerHTML = "<div> /* dynamic div contents */ </div>"
Its the simplest way, as if you are using html element in ASP.net use dom controls for better generation. Dynamic creation of control will require handled, interface and many things to co-ordinate with that control. As its not predefined by system. you have to create it.
SO choose the DOM element option. that is faster and better :)
I hope this will help :)
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.