cannot access js code in content page - asp.net

I took one masterpage and one web form selected with the first master page.
In this webform i took textbox and button. Button's OnClientClick property set with validate()
I took one JScript.js file in that i write the following function :
function validate() {
var no = document.getElementById('<%=TextBox1.ClientID %>').value;
if (isNaN(no)) {
alert('not a number.');
}
}
In default.aspx page i write the textbox and button code is as following
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" onclientclick="validate()" Text="Button" />
In master page's head section i call the js file as following :
<script src="JScript.js" type="text/javascript">
</script>
So the my question is this is not worked the alert message not appears as i write non numeric number in textbox.

You can't use asp .net binding syntax in js files.
this will be rendered the same in your js file, and will not contain ur TextBox1ClientId:
var no = document.getElementById('<%=TextBox1.ClientID %>').value;
either pass the client Id from your aspx page as a parameter to the validate method, or embed your javascript function in ur aspx.

You can add clientIDMode="Static" in your control.
<asp:TextBox ID="TextBox1" runat="server" clientIDMode="Static"></asp:TextBox>
<asp:Button ID="Button1" runat="server" clientIDMode="Static" onclick="Button1_Click" onclientclick="validate()" Text="Button" />
Or if you want to make it project level, just add the line in web config file
<pages clientIDMode="Static"></pages>
inside <system.web>.

Related

How to use a custom ValidatorUpdateDisplay function when the controls / validators are loaded on postback in an UpdatePanel the first time?

In ASP.NET when using validation controls (i.e. RequiredFieldValidator) the client sided framework will execute the JS function Page_ClientValidate. This function will validate all controls on the page (of the given ValidationGroup) and call the JS function ValidatorUpdateDisplay with a parameter of the DOM element of the span tag of the validator control.
ValidatorUpdateDisplay toggles the visibility of the span tag depending on the result of the validation.
In my web application I've overridden the ValidatorUpdateDisplay JS function to provide more functionality on the validation scenario (i.e. red borders around the controls, showing popover on the first failed control and scrolling to it).
Now this works very well until my controls (incl. submit button) are shown the first time after a postback in an UpdatePanel.
<asp:ScriptManager runat="server" />
<asp:UpdatePanel ID="upTest" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="bShow" runat="server" UseSubmitBehavior="false" Text="SHOW" OnClick="bShow_Click" />
<asp:Panel ID="pContent" runat="server" Visible="false">
<asp:TextBox ID="tbTest" runat="server" />
<asp:RequiredFieldValidator ID="rfvTest" runat="server" ControlToValidate="tbTest" Text="Not valid" />
<asp:Button ID="bTest" runat="server" UseSubmitBehavior="false" Text="TEST" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
function ValidatorUpdateDisplay(val) {
debugger; // this will not be reached
}
</script>
protected void bShow_Click(object sender, EventArgs e)
{
this.pContent.Visible = true;
}
After initial load press bShow to display pContent.
Now, if you leave tbTest.Text empty and press on bTest it should enter the overridden ValidatorUpdateDisplay function, however it enters the function of the framework and displays "Not valid" from rfvTest.
If you change pContent.Visible to true and press bTest after initial load the desired effect will happen: It will enter the custom ValidatorUpdateDisplay function and not display "Not valid".
If you move the button bTest out of the UpdatePanel the problem persists.
How can I make it work inside an UpdatePanel?
ASP.NET uses a lazy loading approach to insert the ValidatorUpdateDisplay function when it needs it the first time, hence in my example it will load the function after the postback of the UpdatePanel.
This will override my own implementation of the ValidatorUpdateDisplay function, because it's inserting the function at the end of the page.
There is a dirty workaround, I just inserted an empty CustomValidator on initial load that is always valid:
<asp:CustomValidator runat="server" />
I wish there was a cleaner solution.

How to access user control page dropdownlist control id from main page's javascript function?

main page :
<%# Register TagPrefix="A" TagName="AA" Src="~/UserControls/ab.ascx" %>
<A:AA id="a1" runtat="server" />
<asp:Button ID="btn" Visible="true" runat="Server" OnClick="Btn_Click" OnClientClick="javascript:PreLoad();" />
<script type="text/javascript">
function PreLoad() {
var empty = '<%= (a1.FindControl("ddl")).ClientID %>';
// the above line giving error as 'ddl is inaccessible due to its protection level'
}
</script>
in Usercontrol page:
<%# ControlLanguage="C#" AutoEventWireup="true" CodeBehind="ab.ascx.cs" inherits="ab.ascx.designer.cs" %>
<asp:DropDownList ID="ddl" runat="server"> </asp:DropDownList>
in ab.ascx.designer.cs
protected global::System.Web.UI.WebControls.DropDownList ddl;
Someone please explain the clean and simple proper way to access the 'ddl' inside the 'PreLoad()'
javascript function?
Change your tag to:
<asp:DropDownList ID="ddl" runat="server" ClientIDMode="static"> </asp:DropDownList>
This means that the control is rendered using the exact ID that you specified.
Then change your javascript to use the exact id of the control and access it by:
document.getElementById("ddl");
Or with jQuery:
$("#ddl");
Ideally you should move this javascript code to an external file too.

code behind with postback url

I try to make postpackurl in code behind so that I can send the code but my issue is when I click the button its keep it in the same page .
my question is how I can make the postbackurl directly go to next page?
Asp.net Button Has property named postbackurl which you can set postbackurl:
<asp:button id="Button2"
text="Post value to another page"
postbackurl="Button.PostBackUrlPage2cs.aspx"
runat="Server">
</asp:button>
Use
response.redirect("frmdefault.aspx")
in your button click code.
In the ASPX file add the below Script:-
<script type="text/javascript">
function SomeMethod() {
window.location.reload("nextpage.aspx");
return false;
}
</script>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return SomeMethod();"/>
When the user clicks on the button1 the nextpage.aspx page will be executed and no postback will happen on the current page

Server Control Auto Postback with form has _blank attribute

My case is I have an asp.net page has a form
<form id="form1" runat="server" target="_blank">
and a button redirect to another page and this page will open in a new window because of the target attribute of the form .
<asp:Button ID="button1" runat="server" PostBackUrl="~/kindofpage.aspx" Text="Generate" />
and I have a dropdownlist has auto postback = true to post the past to fill another dropdownlist by selected data .
<asp:dropdownliast id="Make" name="Make" runat="server" autopostback="true"></asp:dropdownlist>
the question is : why when I select item from the auto postbacked dropdown an blank page opened ?
I need a way to post the page by the dropdownlist without openning a blank page ..
Thank you,
For lack of a better idea, you could just remove the target="_blank" attribute from your markup, and when your button is clicked, modify the form tag with JavaScript and set the attribute.
You can set the OnClientClick property and run JavaScript when it's clicked. For example:
<asp:Button ID="button1" OnClientClick="document.getElementById('form1').setAttribute('target', '_blank')" runat="server" PostBackUrl="~/kindofpage.aspx" Text="Generate" />
You could always just adjust your buttonpress code to open a new window such as this:
<asp:Button ID="myBtn" runat="server" Text="Click me"
onclick="myBtn_Click" OnClientClick="window.open('kindofpage.aspx', 'kindofpage');" />
then remove the:
target="_blank"
From the form tag.
I struggled with a similar situation but solved it in the following way.
As mentioned in this answer, you can use the OnClientClick property to set the target to "_blank". E.g.
<asp:Button ID="button1" OnClick="codebehind_method" OnClientClick="document.forms[0].target = '_blank';" runat="server" Text="targets new window" />
Then, in the aspx page that my "codebehind_method" function redirects to, I reset the target of the opener form like so:
<script type="text/javascript">
function resetTarget() {
opener.document.forms[0].target = '';
}
</script>
<body onload="resetTarget()">
Now, if you go back to your opener form and use a control that does not have the "OnClientClick" property set, the AutoPostBack should occur in the same tab.
If you want to find your form by ID, replace "document.forms[0]" with:
document.getElementByID('yourFormName')
<form id="form1" runat="server">

Update Panel and triggers from a repeater control

Hi I found code similiar to the following online. It's seems really great for getting a button buried in a repeater control to trigger a full cycle back to the server.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<%=DateTime.Now.ToString() %>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="HiddenButton" />
</Triggers>
</asp:UpdatePanel>
<!--Make a hidden button to treat as the postback trigger-->
<asp:Button ID="HiddenButton" runat="server" Style="display: none" Text="HiddenButton" />
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<!--when cick the button1, it will fire the hiddenButton-->
<asp:Button ID="Button1" Text="Trigger" CommandArgument='<%# Eval("Id") %>' OnClientClick="$get('HiddenButton').click();return false;"
runat="server" />
</ItemTemplate>
</asp:Repeater>
It uses a hiddenButton to achieve this by hooking the click event of the original button to this one. However my addition to this was the setting of the CommandArgument for the button. I would also need it to be set for the HiddenButton.
Does anyone know a way of going about this?
First I will like to explain the Disadvantage of using the Update Panel using the very same example posted by you.
Below is the Original Code
Output
To display the 22 character string you can check how much data is being received and sent to server. Just imagine following
If you would consider send each request to Database using Update Panel and your GridView is in Update Panel!!!!!!
Suppose you would use ViewState data for each request and with GridView Inside the Update Panel.
Both the above techniques are worst as per my understanding.
Now I will describe you Page Methods
Page Method over Update panel
Page Methods allow ASP.NET AJAX pages to directly execute a Page’s Static Methods, using JSON (JavaScript Object Notation). Instead of posting back and then receiving HTML markup to completely replace our UpdatePanel’s contents, we can use a Web Method to request only the information that we’re interested.
Sample Code
Output
Hope this clearly explains the difference of usage.
Answer to the original Query
You have to register the ItemDataBound event of the below Repeater and use below code for it.
Code Behind
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
Button btn = (Button)e.Item.FindControl("Button1");
btn.OnClientClick = string.Format("SubmitButton('{0}');return false;"
, HiddenButton.ClientID);
}
}
JavaScript
<script type="text/javascript">
function SubmitButton(btn)
{
$("#" + btn).click();
}
</script>
//Alternative
<script type="text/javascript">
function SubmitButton(btn)
{
document.getElementById(btn).click();
}
</script>
Reference & Here
Your HiddenButton control is a server control but you are trying to access it in JQuery using it's ASP.Net ID,
<asp:Button ID="Button1" Text="Trigger" CommandArgument='<%# Eval("Id") %>' OnClientClick="$get('**HiddenButton**').click();return false;"
runat="server" />
A quick way to fix it is to make a separate function,
<script type="text/javascript">
function SubmitButton(btn)
{
$get("#" . btn).click();
}
</script>
and change your button code to ,
<asp:Button ID="Button1" Text="Trigger" CommandArgument='<%# Eval("Id") %>'
runat="server" />
In code behind, in repeater's ItemDataBound event, find the button and HiddenControl and set Button1's OnClientClick property,
Button1.OnClientClick= string.Format("SubmitButton('{0}');return false;",HiddenButton.ClientID);

Resources