I am using telerik RadTextBox inside asp.net User Control page.
I have writen below Jquery validation code inside main content page as shown below, I am trying to set RadText box name attribute as static inside User Control so that I can use it in Main Content page.
User Control page
<telerik:RadTextBox ID="txtProductPrice" ClientID="txtProductPrice"
runat="server" ClientIDMode="Static" />
Main Content Page:
$("#aspnetForm").validate({
rules: {
ctl00$ContentPlaceHolder1$ucUserInfoI$txtProductPrice: {
required: true,
number: true,
maxlength: 5
},
}
});
I have used dynamically generated name attribute to validate the textbox, which looks ugly.
Since RadTexBox is in UserControl page , I am not able to use RadTexBox with UniqueID in main content page as below:
$("#aspnetForm").validate({
rules: {
<%=txtProductPrice.UniqueID %>:{
required: true,
number: true,
maxlength: 5
},
}
});
Any idea how to I can use RadTexBox with UniqueID in main content page ?
Any help would be great.
These steps can prove helpful to you:
1. For client-side logic, you can try using <%=txtProductPrice.ClientID %> instead of UniqueID.
2. Telerik controls are complex server and script controls and you should not use ClientIDMode="Static" with them. Details
3. Make sure you have the following setting in your web.config file as suggested by Sparky:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/>
Here are some Details and More Details.
4. You can always use the $telerik.findControl method to manually access the RadTextBox and execute your custom logic. Details
Related
I'm seeking advice on how to best encapsulate this HTML markup and behavior for extensive reuse.
I've developed a working version of some "context sensitive" help on a given .aspx page that uses the qTip2 plugin for jQuery ("squeezed up" here for completeness for the question):
$('a.myMore[title]').qtip({
content: { title: { button: true } }
, style: { classes: 'qtip-youtube myCustomClass' }
, position: { target: 'mouse', adjust: { x: 5, y: 5} }
, show: { effect: function() { $(this).fadeTo(500, 1); } }
, events:{hide:function(event, api) {if (event.originalEvent.type !== 'click') return false;}}
});
Here is a sample of the the markup operated upon by the plugin above that I'd like to encapsulate:
<a class="myMore" href="#" title='Text here will be displayed by a jQuery plugin called qTip2'>
<img src='../images/icon/info1.png' alt='?' />
</a>
This is in an older environment of Visual Studio 2008 webforms using VB.Net. One thread on SO expressed my need very well - see MVC3 Razor views - but the only encapsulation approach I can think of is writing an ASP.Net web user control (.ascx) to dump out the HTML I need. I envision being able to sprinkle something like this throughout my .aspx pages:
<qTipH:qTipHelper Title="Here is some content for the qTip." runat="server" />
Am I on the right track given the "old-ish" environment in which I have to work?
I started in on writing this control and immediately noticed there is no title attribute for any of these server controls - <asp:HyperLink nor <asp:ImageButton nor <asp:LinkButton. I don't think the code-behind of the user control can inject the title attribute text into a standard HTML <a> tag.
I think I know what I need rendered but I'm looking for advice on the best approach. Thanks.
EDIT - UPDATE:
So here is my .ascx file I came up with:
<%# Control Language="vb" AutoEventWireup="false"
CodeBehind="qTipHelper.ascx.vb"
Inherits="myProjectName.qTipHelper" %>
<asp:HyperLink ID="HyperLink1" runat="server" CssClass="myMore"></asp:HyperLink>
I discovered that any "missing" attributes like "title" can be handled by the following code-behind which adds to the Attributes collection of the control:
Public Partial Class qTipHelper
Inherits System.Web.UI.UserControl
Public Title As String = Nothing
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Title Is Nothing OrElse Title = "" Then
Visible = False
Else
Dim encodedTitle As String = Server.HtmlEncode(Title)
HyperLink1.Attributes.Add("title", encodedTitle)
HyperLink1.Attributes.Add("href", "#")
HyperLink1.ImageUrl = "../images/icon/info1.png"
End If
End Sub
End Class
On my invoking page(s), I added this:
<%# Register TagPrefix="qTip" TagName="qTipHelper" Src="~/UserControls/qTipHelper.ascx" %>
and then to spit out the HTML, I added this:
<qTip:qTipHelper runat="server" title="grist for the mill courtesy of qTip" >
</qTip:qTipHelper>
Is there a coding technique that could be added to the user control that would emit one Javascript script block at the bottom of the page (assuming that one or more tags for qTipHelper were present in the HTML above)?
In retrospect, this is weird question (I think because I never had to do anything like this before)...
Anyway, I simply collected all my current uses of qtip in a single Javascript file which I reference at the bottom of each .aspx page that uses it like this:
<script type="text/javascript" src="<%= ResolveClientUrl("~/js/qTipCode.js") %>"></script>
So, this boils down to:
1. writing a single user control
2. registering the user control on .aspx content pages that will need it
3. sprinkling the .aspx content page with the user control tag whereever it is needed
4. adding the script tag to point to the qtip Javascript file
5. ensuring that the selectors in the jQuery "match up" with the HTML markup on the page
I hope this helps someone else. I have learned alot about new stuff trying this.
In asp.net I took one master page and one Web Form selected with the master page.
In first web form i have one textbox and button.
When button click then OnClientClick property contains validate() function
Now In master page's coding I written as following :
function validate() {
var no = document.getElementById('<%=Page.Master.FindControl("ContentPlaceHolder1").FindControl("TextBox1").ClientID %>').value;
if (isNaN(no)) {
alert('not a number.');
}
}
Now i took second web form
In that i put one calendar control and just run it
error occurs as following :
Object reference not set to an instance of an object.
Line 11: function validate() {
Line 12: var no = document.getElementById('<%=Page.Master.FindControl("ContentPlaceHolder1").FindControl("TextBox1").ClientID %>').value;
Line 13: if (isNaN(no)) {
Line 14: alert('not a number.');
I am seeing Line 12 : as a red line.
So How to run this second Web Form
Inside content page declare an in-line Javascript variable.
<script>
var jsTextBox1Id = <%=TextBox1.ClientID%>;
</script>
Now you can access the control ID in Validate() using global jsTextBox1Id variable.
Like this:
var no = document.getElementById(jsTextBox1Id).value;
(Remember this type of approach is not a recommended practice.)
Update
To get a reference to the HTML element that is rendered for any control in client script, you must know the value of the control's ClientID property. However, because the user control can be put anywhere in a Web page, it is impossible to know in advance which naming containers will contain the controls. To make sure that the ClientID value will be the same as the ID value, the just set the ClientIDMode value to Static.
<asp:TextBox ID="MyStaticId" runat="server" ClientIDMode="Static">
</asp:TextBox>
Now you can access it using the ID defined by you MyStaticId, it will not have prepended parent container name to it.
document.getElementById("MyStaticId").value
Source MSDN
I am trying to insert a captcha in my ASP.NET code. Basically, in the lbt_proceed_click() method, I want the browser to proceed to the next page using Response.Redirect("foo") only if the captcha entered is correct.
I searched, but could not find a solution, especially since I am not using a form to send data, but writing to a database directly, and then moving to the next page using Response.Redirect().
go to the reCAPTCHA site and register for a unique key
Download reCAPTCHA .NET Library
Create and Save your Public and Private keys safely
In the website we add a reference to library/bin/Release/Recaptcha.dll
after the #Page directive, insert the following code:
<%# Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha"%>
add control in asp.net tag:
<recaptcha:RecaptchaControl
ID="recaptcha"
runat="server"
PublicKey="Your very own public key here"
PrivateKey="Your very own privat key here"
/>
add button and label to your form
add the following button click method(btnSubmit_Click) in code behind file :
if (Page.IsValid)
{
lblResult.Text = "You Got It!"; // Or Use Response.redirect("foo");
}
else
{
lblResult.Text = "Incorrect";
}
Test your Page!
Question: What is the best way to set focus to a web control in ASP .NET.
I can do it, but it's ugly. I have a web control wrapped in a web control hosted on a web page. So, if you do a view | source on the page the id is something like WrapperControl_Control_TextBox.
I've tried the "tried and true" Javascript methods of grabbing the element and setting it's focus: document.getElementByID( "WrapperControl_Control_TextBox" ).focus(); and it didn't work. I'm not sure why.
I know I could possibly do:
document.getElementById( "<%= TextBox.ClientID %>" ).focus(); too, I think. This won't work because of another totally separate error based on the fact you can't dynamically add controls to a header if there is a "<% %>" in the page. GAH.
In the "bottom-most" control, I've tried setting the focus (TextBox.Focus() in Page_Load) and that doesn't work either.
Anyway, the way that works is by simply taking the ControlsCollection of the Page, grabbing the control I need from that, getting it's collection, grabbing the next lower control and so forth.
I only have to do this seven times. So I have eight foreach loops.
Basically, my code is like this:
///////////////////////////////
// On the page
///////////////////////////////
ControlCollection controls = Controls;
foreach( Control control in controls)
{
if ( string.Equals( control.ID, "FormID", StringComparison.InvariantCultureIgnore ) )
{
ControlCollection nextControls = control.Controls;
foreach( Control nextControl in nextControls )
{
if ( string.Equals( nextControl.ID, "DivICareAboutInTheForm", StringComparison.InvariantCultureIgnor ) )
{
ControlCollection nextNextControls = nextControl.Controls;
//:
//:
//Yes, it's that bad and so forth.
//:
//:
}
}
}
}
You can use jQuery to do a search for IDs that end with your textbox name. This way you wont have to call the UniqueID server-side code. Just make sure not to have multiple controls that end with the same name
<script type="text/javascript">
$(document).ready(function() {
$('[id$=txtBox]').focus();
});
</script>
Or, you can use a Class name for the default text box.
<asp:Textbox ID="txtBox" runat="server" cCssClass="defaultTextbox" />
jquery:
$('.defaultTextbox').focus();
You can get around the "cannot add dynamic controls because a <%= %> block exists on the page" error by changing the block to use databinding syntax: <%# TextBox.ClientID %>, and manually calling Page.DataBind() in Page_Load.
If you really want to use the Page_Load method, then you could always call the SetFocus method on the Page object.
Page.SetFocus(myTextBox);
Is it possible to add a new ServiceReference instance to the ScriptManager on the Page during an asynchronous postback so that subsequently I can use the referenced web service through client side script?
I'm trying to do this inside a UserControl that sits inside a Repeater, that's why adding the ScriptReference programmatically during Page_Load does not work here.
EDIT 2: This is the code I call from my UserControl which does not do what I expect (adding the ServiceReference to the ScriptManager during the async postback):
private void RegisterWebservice(Type webserviceType)
{
var scm = ScriptManager.GetCurrent(Page);
if (scm == null)
throw new InvalidOperationException("ScriptManager needed on the Page!");
scm.Services.Add(new ServiceReference("~/" + webserviceType.Name + ".asmx"));
}
My goal is for my my UserControl to be as unobtrusive to the surrounding application as possible; otherwise I would have to statically define the ServiceReference in a ScriptManagerProxy on the containing Page, which is not what I want.
EDIT:
I must have been tired when I wrote this post... because I meant to write ServiceReference not ScriptReference. Updated the text above accordingly.
Now I have:
<asp:ScriptManagerProxy runat="server" ID="scmProxy">
<Services>
<asp:ServiceReference Path="~/UsefulnessWebService.asmx" />
</Services>
</asp:ScriptManagerProxy>
but I want to register the webservice in the CodeBehind.
Try something like this...
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "script1", "~/js/myjs.js");
}
Edit:
After checking your issue, Here is the reason why it is not working:
When you add ServiceReference to ScriptManager > Services section manually in page. It adds 1 client script include directive.
e.g:
<script src="TestService.asmx/jsdebug" type="text/javascript"></script>
or
<script src="TestService.asmx/js" type="text/javascript"></script>
which provide you to accessibility to your Frontend.Web.YourScriptMethods,
Now when you add ServiceReference in async postback - It is not adding this client script inclue. So you get client script error - method is undefined.
But i figured out a workaround for this; (do not know it is right way to do it)
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "testservice", "TestService.asmx/js");
}
You can replace the "TestService.asmx" path according to your project/web service.
This way you can achieve what you want.
Hope this helps,
Krunal Mevada
Old Ans:
Use following:
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
ScriptManager.GetCurrent(this).Services.Add(new ServiceReference("~/Service.asmx"));
}