How to reference multiple identical user controls on a page - javascript

I'm trying to use several instances of an ascx control on a single page. Only the last control on the page works. I understand from this post [Asp.Net User Control does not work correctly when multiple are added to one form that the problem is related to the IDs; somehow I'm trying to reuse the IDs and the specific control being edited is not referenced correctly. However, the code on that page is complex and I don't understand the answers. I created a small example of my problem to demonstrate.
Here is my user control:
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="testControl.ascx.vb" Inherits="Tempusforms.testControl" %>
<script type="text/javascript">
function getValue() {
document.getElementById("<%=Label1.ClientID %>").innerHTML = getIndex();
}
function getIndex() {
return document.getElementById("<%=droppit.ClientID %>").selectedIndex;
}
</script>
<span>
<asp:DropDownList ID="droppit" runat="server" OnChange="getValue();" >
<asp:ListItem Value="Select a Value"></asp:ListItem>
<asp:ListItem Value="one"></asp:ListItem>
<asp:ListItem Value="two"></asp:ListItem>
<asp:ListItem Value="three"></asp:ListItem>
</asp:DropDownList>
</span> Index Value =
<span>
<asp:label ID="Label1" runat="server" Text="mylabel" ></asp:label>
</span>
Here is the page that uses the controls:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="userControlTest.aspx.vb" Inherits="Tempusforms.userControlTest" %>
<%# Register src="../Common/testControl.ascx" tagname="testControl" tagprefix="uc1" %>
<!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>
<uc1:testControl ID="testControl1" runat="server" />
<br /><br />
<uc1:testControl ID="testControl2" runat="server" />
</div>
</form>
</body>
</html>
Can you show me how to make this work?
Thanks for your help.

ASP.NET generates different IDs which include the UserControl ID so IDs aren't the issue here.
However the problem is with the JS code that you are including in the User Control. This gets repeated and bad things happen because of that obviously.
You should get those scripts outside the User Control and change them to use parameters.
Something like:
<script type="text/javascript">
function getValue(ctrlID) {
document.getElementById(ctrlID).innerHTML = getIndex(ctrlID);
}
function getIndex(ctrlID) {
return document.getElementById(ctrlID).selectedIndex;
}
</script>
And you can call these functions from the User Control like this: OnChange="getValue(this.id);"

Related

InvalidOperationException: WebForms UnobtrusiveValidationMode in C#

I've a web form with a text box and RequiredFieldValidator Control.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Name : <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate ="TextBox1" ErrorMessage="RequiredFieldValidator">
</asp:RequiredFieldValidator>
<asp:button runat="server" text="Button" />
</div>
</form>
</body>
</html>
When I load the page and click on the button, I get an error saying
Error:
[InvalidOperationException: WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).]
System.Web.UI.ClientScriptManager.EnsureJqueryRegistered() +145
System.Web.UI.WebControls.BaseValidator.RegisterUnobtrusiveScript() +11
System.Web.UI.WebControls.BaseValidator.OnPreRender(EventArgs e) +88
System.Web.UI.Control.PreRenderRecursiveInternal() +166
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4682
I did some googling and found some solutions like changing the target version to 4.0 in web.config, using jquery in the global.asax file and changing the property of UnobtrusiveValidationMode to none.
I even read about unobtrusive javascript at https://en.wikipedia.org/wiki/Unobtrusive_JavaScript. But I could not make any relation with the content given there and the error I encountered
Most of the answers said to refer http://connect.microsoft.com/VisualStudio/feedback/details/735928/in-asp-net-web-application-visual-basic-the-requiredfieldvalidator-doest-work
But this link no longer exists.
When I viewed the source of the web page after changing the target version to 4.0, I found some extra inline javascripts(I guess that's called obtrusive javascripts). What's wrong in using inline codes?
I'm pretty new to ASP.net, so little brevity appreciated.

ASP.NET setting textbox value using javascript without document.getElementById()

I have the following Web Form in my ASP.NET Website
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ValidateRequest="false" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function SetTextBoxValues() {
TextBox1.value = "Textbox can be set without calling document.getElementById()";
TextBox2.value = "Textbox can be set without calling document.getElementById()";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" Height="210px" TextMode="MultiLine" Width="725px"></asp:TextBox>
<br/>
<textarea rows="4" cols="50" id="TextBox2" runat="server" />
<br/>
<button onclick="SetTextBoxValues()">Set Text Box Value</button>
</form>
</body>
</html>
The page works as I can click the button and set values in both TextBox1 and Textbox2. What I don't understand is the way the Textbox value is set in the javascript function.
<script type="text/javascript">
function SetTextBoxValues() {
TextBox1.value = "Textbox can be set without calling document.getElementById()";
TextBox2.value = "Textbox can be set without calling document.getElementById()";
}
Normally we need to use the following JS code:
document.getElementById('<%=txtTextBox.ClientID %>').value = "Some values";
But it looks like we can set the value without the use of document.getElementById(). May I know why it is working this way? Is this a valid way of setting textbox value using javascript?
You use component "runat server" so you should use code behing:
TextBox2.Text = yourvalue;
And create a method server side to manage your inputs.
I think it's like this post:
textarea control, asp.net c#
quoting answer provided as comment from ConnorsFan.
It does work, indeed. I think the explanation is given here:
stackoverflow.com/questions/3434278/…. – ConnorsFan Jun 3 '16 at 12:29

Targetting an element within an Ajax control

I am trying to create a custom button in an Ajax HtmlEditorExtender control by locating the button container using its css class and appending a new button. However I am stuck at the first stage in that I cannot locate the container:
either in JQuery:
$btnContainer = $(".ajax__html_editor_extender_buttoncontainer");
window.alert($btnContainer.length);
Alert produces 0 even though there are buttons in the container
or in vanilla jscript:
var x = document.getElementsByClassName("ajax__html_editor_extender_buttoncontainer");
window.alert(x.length);
alert again produces 0
Other elements on the page with css class names can be located in this way but the elements within the Ajax control cannot be found (even though they show up in Firebug with the above css class name).
Can anyone help please?
Added 04/06/15
Many thanks for the suggestions. Finding the control is indeed a timing and postback issue and not to do with getting the element within another control. If I strip out all except the vital bits, this is the code below.
Wherever I put the call to the JQ function, it cannot find the item wanted. None of the (commented out) ways of calling it work. Only if launched from a button on the page will it work. Have also tried calling the JQ from codebehind at page.LoadComplete but that is also too soon it seems.
Any help appreciated.
<%# Page Language="VB" AutoEventWireup="false" CodeFile="EventsEdit.aspx.vb" Inherits="admin_EventsEdit"
ValidateRequest="false" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" 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></title>
<script type="text/javascript" src="../Scripts/jquery-2.0.2.min.js"></script>
<script type="text/javascript">
function showcontainerJQ() {
$btnContainer = $(".ajax__html_editor_extender_buttoncontainer");
alert($btnContainer.length);
$btnContainer.append("<input id=\"HtmlEditorExtender_H1\" class=\"ajax__html_editor_extender_YourButtonName\" type=\"button\" name=\"YourButtonName\" title=\"YourButtonName\" style=\"width: 21px; height: 21px;\" unselectable=\"on\"></input>");
}
//window.onload = showcontainerJQ();
//document.onload = showcontainerJQ();
//body.onload = showcontainerJQ();
</script>
<style type="text/css">
.ajax__html_editor_extender_HtmlEditorExtender_H1
{
background: url('/images/YourButtonName_off.png') no-repeat scroll;
cursor: hand;
display: block;
float: right; /* default is left */
border: medium none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<input type="button" onclick="showcontainerJQ()";value="H1"; > add button</input>
<br /><br />
<asp:TextBox ID="TextBox1" runat="server" Height="400px" Text='<%# Bind("eventText") %>'
Width="265px"></asp:TextBox>
<asp:HtmlEditorExtender ID="TextBox1_HtmlEditorExtender" DisplaySourceTab="true"
EnableSanitization="false" runat="server" Enabled="True" TargetControlID="TextBox1">
<Toolbar>
</Toolbar>
</asp:HtmlEditorExtender>
</div>
</form>
</body>
</html>

Access content page control from master page using javascript

I want to access the content page Ajax combobox control in the master page and that too by using Javascript.
I have been trying the same by using the contentpageholder of the content page, but also one of the problem I get is there are around 10 content pages, so when some other page like Page 1 is opened , the code show object reference exception as contentplaceholder is not matched.
How to get that which content page is opened up?
Also I am not able to get the code working to get the maincontentplaceholder id in master page.
What I have done till now:
function accessControlContentPage() {
var txtCont = document.getElementById("Page.Master.FindControl('ContentPlaceHolder1').FindControl('txtContent')").value;
var text=txtCont;
}
But this is not working.
Any help with the same?
The suggested approach is add a specific content place holder controls for such scripts to be placed in the web page you are rendering. Take a look at the following master/content page markup:
Master page:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebApp.PageMethods.Site1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
There is a content place holder head wherein I must write some js functions trying to access the dropdown list in the other content place holder ContentPlaceHolder1.
Content page markup:
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApp.PageMethods.WebForm3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script>
function foo() {
var ddl = document.getElementById('<%= DropDownList1.ClientID %>');
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
</asp:Content>
Here I didn't have to worry so much about trying to access controls nested in ContentPlaceHolderID.
Alternatively, if you don't have that option/freedom, you can always write something as follows in your master page itself:
var d = document.getElementById('<%= this.ContentPlaceHolder1.FindControl("DropDownList1").ClientID %>');
Access content page control from master page using javascript
we can find div id or control id of content page from master page in asp.net
Explanation of content page:-
don't forgot to mention runat="server",
ContentPlaceHolderID="content_body" //observation,
main_content is the ID of div tag
MasterPage.master
var d = document.getElementById('<%= this.content_body.FindControl("main_content").ClientID %>');
Do whatever you want with d
Thank you

onclick anchor tag, table row become visible using JavaScript?

I have made the same Google map web page with more than two destination to get direction between them. Now whenever I click on add more destination using anchor tag in web page, using JavaScript my table row should be visible in which one textbox for destination and label will be there. So can anybody tell whats the process of handling such situation using JavaScript?
You can check more about my problem by clicking on Google map get directions and adding more destinations. The same I want to do. Can anyone tell me about how to?
If I understood correctly this is what you need:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TableRowShow.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 type="text/javascript">
window.onload = function()
{
document.getElementById('addDestination').setAttribute('onclick', 'addDest();');
}
var i = 1; // position of next tr to be shown
function addDest()
{
var trs = document.getElementById('travelTable').getElementsByTagName('tr');
if (trs[i] != null)
trs[i++].style.display = "";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table id="travelTable">
<tr>
<td>
<asp:TextBox runat="server" />
</td>
</tr>
<tr style="display: none">
<td>
<asp:TextBox runat="server" />
</td>
</tr>
<tr style="display: none">
<td>
<asp:TextBox runat="server" />
</td>
</tr>
</table>
<asp:HyperLink runat="server" ID="addDestination"
ClientIDMode="Static" NavigateUrl="javascript:;" >
Add Destination
</asp:HyperLink>
</form>
</body>
</html>
Code should be pretty much self explanatory but ask if you have any question. :)

Categories