User Control Static Name Option? - asp.net

I know there is a way to force asp web user controls (ascx) to use static ID's so they don't get appended with all the appended naming garbage...but is there way to do the same for the"name" attribute? Specifically, in this case, for DDL's? JQuery needs a specific name and I need to stop .NET from doing this.

Not possible in ASP.Net for now ... I've found this combination to be an acceptable solution.
Add the ClientIDMode="Static" to the control:
<asp:HiddenField ID="HiddenField1" runat="server" ClientIDMode="Static" />
Using JQuery, on document ready, set the name attribute on the control to the value of its id:
$(document).ready(function () {
// alert($("#HiddenField1").attr("name"));
$("#HiddenField1").attr("name", "HiddenField1");
// alert($("#HiddenField1").attr("name"));
});

Try adding ClientIDMode="Static" to the control tag.
<asp:FileUpload ID="FileUpload1" runat="server" ClientIDMode="Static" />

Related

cannot access js code in content page

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>.

How can I use Client ID within a server control?

I was able to do the following in a repeater and it works just fine:
<asp:TextBox ID="txtOtherPartyName" Text='<%# Eval("Name") %>' runat="server" />
<asp:RequiredFieldValidator ID="reqLoss" ControlToValidate="txtOtherPartyName"
data-valmsg-for='<%# Container.FindControl("txtOtherPartyName").ClientID%>'
Display="Dynamic" ErrorMessage="Name of party involved is required." runat="server" />
The data-valmsg-for attribute in the required validator rendered the server control id just fine. How can I do the same for a control that sits on a page and is not within a repeater? I tried similar things without any luck.
Update
So here's what I'm looking to do exactly:
<asp:Textbox id="txtTest" runat="server" />
<asp:RequiredFieldValidator id="reqTest" data-valmsg-for=**[i want the html rendered id of "txtTest" here]** runat="server" />
You can bind that custom attribute to the control's client id in the code behind.
butthead.Attributes.Add("data-custom-prop", beavis.ClientID);
In the Repeater you used databinding syntax (<%# ... %>), but that doesn't apply in this case. You should be able to set the attribute like this:
data-valmsg-for='<%= TextBox1.ClientID %>'
Why are you adding custom attributes to the validators in the first place though, if you don't mind me asking? What purpose does it serve that can't be achieved through other means?
EDIT
Have you considered building your list of control IDs in code-behind beforehand, and storing it somewhere? Could something like this be a starting point?:
var controlList = Page.Validators.OfType<BaseValidator>()
.Select(v => Page.FindControl(v.ControlToValidate).ClientID).ToList();
EDIT
Expanding on that idea, you can serialize the list to JSON using the JavaScriptSerializer (System.Web.Script.Serialization):
//initialize the javascript serializer
var serializer = new JavaScriptSerializer();
//retrieve all of the validators on the page and store the client ids in a list
var controlList = Page.Validators.OfType<BaseValidator>()
.Select(v => Page.FindControl(v.ControlToValidate).ClientID).ToList();
//serialize the control id list and register the script block on the page
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "data", string.Format("var data = {0}", serializer.Serialize(controlList)), true);
Depending on how complex the form is, you may need to create a recursive function to find all of the controls, but hopefully this demonstrates the concept.

how to set Name attribute for HiddenField control server-side?

I want to set the "name" attribute for HiddenField control of ASP.NET from code behind, but I cannot find the "Attributes" property. Is it not there for a purpose? How do I add the attribute?
thanks
The name attribute is automatically computed from the ID properties of the hidden field and its ancestors in the naming container chain. You don't get to set it yourself. You can only access it through the UniqueID of the control.
A possible solution, without knowing a bit more about your code, is to use a server side Html control rather than an ASP.NET web control by adding the runat="server" attribute to the Html markup:
<input type="hidden" id="myHiddenField" runat="server" />
You can then specify the id dynamically in the code behind at runtime from which the name attribute is inferred from:
myHiddenField.ID = "CodebehindName";
myHiddenField.Value = "myValue";
This will result in the following output:
<input name="CodebehindName" type="hidden" id="CodebehindName" value="myValue" />
Another unorthodox method to deal with it is to set the name attribute client side. This is useful if you are posting to a third party such as PayPal.
jQuery EG:
<script type="text/javascript">
$(function () {
$('#BusinessHid').prop('name', 'business')
$('#CurrencyHid').prop('name', 'currency_code')
$('#InvoiceHid').prop('name', 'invoice')
$('#AmountHid').prop('name', 'amount')
})
</script>
<asp:HiddenField ID="BusinessHid" runat="server" ClientIDMode="Static" />
<asp:HiddenField ID="CurrencyHid" runat="server" ClientIDMode="Static" />
<asp:HiddenField ID="InvoiceHid" runat="server" ClientIDMode="Static" />
<asp:HiddenField ID="AmountHid" runat="server" ClientIDMode="Static" />
Forget about the HiddenField control and use a Label instead, give it a name (an id), make it invisible, and store your text into it:
label = new System.Web.UI.WebControls.Label() {
Text = "Here my hidden text",
};
label.Attributes.Add("id", "MyHiddenFieldID");
label.Attributes.Add("style", "display:none;");
myParentControl.Controls.Add(label);
Get your hidden field in your javascript with:
var myHiddenField = document.getElementById("MyHiddenFieldID");
The way I ended up doing this was to set ClientIDMode="Static" on the HiddenField and then set the ID to what I want my name to be.
I ended up with ugly IDs but this was a small price to pay to get this to work.

How to set focus on textbox and/or control after clicking an asp label?

I would like to set the focus on a textbox and/or control after clicking an asp label? Can some explain to me how to do this? Similar to doing a
<label for="txtBoxID">Blah</label>
You can also do this
<label for="<%=txtName.ClientID%>">Name:</label>
<asp:TextBox runat="server" ID="txtName"></asp:TextBox>
or on dot 4.
<label for="txtName">Name: </label>
<asp:TextBox runat="server" ID="txtName" ClientIDMode="Static"></asp:TextBox>
and avoid JavaScript.
This is the Best way to write and avoid javascript
<p>
<asp:Label ID="lblName" runat="server" AssociatedControlID="txtFirstName" Text="First Name: " />
<asp:TextBox ID="txtFirstName" runat="server" />
</p>
You can do it using Javascript or jQuery.
<label for="txtBoxID" onClientClick="SetMyFocus()">Blah</label>
<javascript>
function SetMyFocus()
{
document.getElementById("MyTextBox").focus();
}
</javascript>
If you have a specific need of doing something in the server side on the click of the label, you shall have to handle the same in code behind and then set the client side script to fire up after reloading the page. Use RegisterStartupScript for the same.
I'm assuming you want to do it completely on the client side to avoid a postback?
You can use jQuery to set focus. After adding a script reference to the jQuery library, you can use the following JavaScript in your page:
$(document).ready(function() {
$("#labelId").click(function() {
$("*[id$='txtBoxID']").focus()
});
});
The "*[id$='txtBoxID']" selector allows you to select the ASP.NET server side ID of your textbox without any additional code. Basically, it's saying "select any DOM element whose ID ends with txtBoxId."
You can add jQuery to your page with the following CDN script reference:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
A more generalized solution using jQuery:
$(document).ready(function() {
$("label[for]").click(function() {
var inputid = '#' + $(this).attr('for');
$(inputid).focus();
});
});
Should handle all labels, as long as you correctly define the for attribute.

Asp.net, directly assigning properties from value?

Is there a way to express
<% objControl.ObjProp=ObjVar; %>
<my:Control ID="objControl" runat="server" />
As something like this, in one line? And without passing ObjVar as a string?
<my:Control ID="objControl" runat="server" ObjProp=ObjVar />
Unless you're in a databound context, no there's no simple way to do this. If it is a databound context (Like in a repeater/gridview) you can simply go ObjProp='<%# ObjVar %>', but outside that context you can't do it inline unfortunately.
use it like
<my:Control ID="objControl" runat="server" ObjProp="<%# ObjVar %>" />
As fyjham has mentioned, you need to do this in a databound context with the <%# %> syntax. If you are trying to set the property dynamically then your other option is to set it within the server side parent's onload code behind method.
What is ObjVar? If it's a static value, you can just add the attribute tag to the control element like so....
<my:Control ID="objControl" runat="server" MyCustomBooleanProperty="true" />
If it's a member variable of the page containing the control, then I'd do so in the code behind...
protected Page_Init()
{
this.objControl.ObjProp = this.ObjVar;
}
If you're databinding to the control, then the others are correct where you use the databinding context.
<my:Control ID="objControl" runat="server" ObjProp=<%#Eval("ObjVar")%> />

Resources