C# ASP.NET document.getElementById not getting elments - c#

I have done searches for this but could not find an answer that worked.
I am trying to access the asp:TextBox ID="wordList" node details and its keep return count = 0. I have tried two alternate methods as can be seen below in the javascript and do not understand why its not working. Can anyone see the reason?
Many Thanks
Jaie
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Week3.WebForm1" Theme="Theme1"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Grid Details</title>
</head>
<body>
<script lang="javascript" type="text/javascript" >
function ValidateWordList() {
var x = document.getElementById("wordList").innerHTML;
x += "Length" + x.length;
alert(x);
var z = document.getElementById('<%= wordList.ClientID %>').innerHTML;
alert(z);
return false;
}
</script>
<form id="form1" runat="server">
<div class="form1Box">
<br />
<asp:Label ID="lblWord" runat="server" Text="Word(s) of Puzzle:"><asp:TextBox ID="wordList" runat="server" ClientIDMode="Static"/></asp:Label>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorWordList" ControlToValidate="wordList"
CssClass="Validation" runat="server" Text="(Required)" />
<asp:RegularExpressionValidator ID="RegularExpressionValidatorWordList" ControlToValidate="wordList" runat="server" CssClass="Validation"
ValidationExpression="(^[a-zA-Z ,]*$)" ErrorMessage="(The word(s) can only be letters, space or comma's!)"/>
<asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" Text="Generate Puzzle" runat="server" OnClientClick="return ValidateWordList()"/>
</div>
</form>
</body>
</html>

Are you trying to retrieve whatever value user has entered in the textbox? If so, you are probably looking for:
var x = document.getElementById("wordList").value;
Text fields do not define any inner markup, and their property innerHtml in most cases is just an empty string.

Related

Performing both client side and server side functions on button click - Specific Scenario

I have a checkbox, label and button control.
If the checkbox is not checked and button is clicked, I need to display a message in label stating to check the checkbox first.
If the checkbox is checked and then the button clicked, it should allow me to proceed.
This is very similar to the terms and conditions screens,where if you dont check the checkbox - you are not allowed to proceed.
I am using the below javascript. Please let me know how do I accomplish this functionality?
<script type="text/javascript">
function testCheckbox() {
var obj = document.getElementById('<%= chkTerms.ClientID %>');
if (obj.checked == false) {
document.getElementById("lblCheck").style.visibility = "visible";
return false;
}
}
</script>
<asp:Label ID="lblTerms" runat="server" Text="I agree to the Terms and Conditions"> </asp:Label>
<asp:Label ID="lblCheck" runat="server" Text="Please agree to the terms and conditions to proceed"></asp:Label>
<asp:Button ID="btnProceed" runat="server" OnClientClick ="return testCheckbox()" OnClick="btnProceed_Click" Text="Submit" />
ASPX:
<%# 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 src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#lblCheck').hide();
$('#btnProceed').click(function () {
var $this = $('#chkTerms')
if ($this.is(':checked')) {
$('#lblCheck').hide();
return true;
} else {
$('#lblCheck').show();
return false;
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:CheckBox ID="chkTerms" runat="server" Text="I agree to the Terms and Conditions"/><br />
<asp:Label ID="lblCheck" runat="server" Text="Please agree to the terms and conditions to proceed"/><br />
<asp:Button ID="btnProceed" runat="server" Text="Submit" onclick="btnProceed_Click1" />
</form>
</body>
</html>
Code behind:
protected void btnProceed_Click1(object sender, EventArgs e)
{
Response.Write("DD");
//your proceed
}

ASP.NET C# Button OnClick even not firing

I've absolutely exhausted Google and I can't find a solution to this problem. When click a button on my .aspx page, the corresponding function is not called from .aspx.cs file. I'll just post my code and see if there are any takers.
AddUser.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="AddUser.aspx.cs" Inherits="AddUser" %>
<asp:Content ID="tb_AddUserHeader" ContentPlaceHolderID="tb_HeaderPlaceHolder" Runat="Server">
</asp:Content>
<asp:Content ID="tb_AddUserContent" ContentPlaceHolderID="tb_ContentPlaceHolder" Runat="Server">
<h1>Add User</h1>
<fieldset>
<asp:Label ID="tb_lblAddUser_Authorized" runat="server" Visible="false">
<br />
<table>
<tr>
<td><u>Username:</u></td>
<td><asp:TextBox ID="tb_txtbxUsername" runat="server" Width="200"></asp:TextBox></td>
</tr>
<tr>
<td><u>Password:</u></td>
<td><asp:TextBox ID="tb_txtbxPassword" runat="server" Width="200" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td><u>Account Type:</u></td>
<td><asp:DropDownList ID="tb_ddAccountType" runat="server">
<asp:ListItem Value="v" Text="Viewer"></asp:ListItem>
<asp:ListItem Value="t" Text="Tester"></asp:ListItem>
<asp:ListItem Value="a" Text="Admin"></asp:ListItem>
</asp:DropDownList></td>
</tr>
<tr>
<td><asp:Button ID="tb_btnAddUserSubmit" runat="server" Text="Submit" OnClick="tb_btnAddUserSubmit_Click" UseSubmitBehavior="true" /></td>
</tr>
</table>
<br />
</asp:Label>
<asp:Label ID="tb_lblAddUser_Output" runat="server" Visible="false"></asp:Label>
<asp:Label ID="tb_lblAddUser_Unauthorized" runat="server" Visible="true">
<br />Only administrators are authorized to view this page
<br />
<br />
</asp:Label>
</fieldset>
</asp:Content>
and my corresponding codebehind file, AddUser.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using tbBusinessObjects;
using tbWebClientControllers;
public partial class AddUser : System.Web.UI.Page
{
tbWebUserController m_userController;
protected void Page_Load(object sender, EventArgs e)
{
m_userController = new tbWebUserController();
//if (this.IsPostBack)
//{
// String username = tb_txtbxUsername.Text;
// //tb_btnAddUser_Click(sender, e);
//}
//else
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
if (ticket.UserData == "a")
{
tb_lblAddUser_Authorized.Visible = true;
tb_lblAddUser_Unauthorized.Visible = false;
}
}
}
}
protected void tb_btnAddUserSubmit_Click(object sender, EventArgs e)
{
tbUser user = new tbUser();
user.m_username = tb_txtbxUsername.Text;
user.m_password = tb_txtbxPassword.Text;
user.m_type = tb_ddAccountType.SelectedValue.ToCharArray()[0];
if (m_userController.InsertUser(user))
{
tb_lblAddUser_Output.Text = "<br />User was successfully added<br /><br />";
}
else
{
tb_lblAddUser_Output.Text = "<br />There was an error adding user<br /><br />";
}
tb_lblAddUser_Output.Visible = true;
tb_lblAddUser_Authorized.Visible = false;
}
}
I've set multiple breakpoints in my Click function and they're never hit. I tried simply catching my Page_Load function with a Page.IsPostBack, but it none of the data is saved from the textboxes or dropdown.
I've also tried changing the UseSubmitBehavior tag between true and false and removing it completely and it still doesn't work. I've copy/pasted as much code from other pages that use button events that are working and it still won't work. I have absolutely no idea what is going on right now. >_<
EDIT: And just in case it would help in any way, here is my Site.master...
<%# Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="SiteMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head id="tb_head" runat="server">
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>KersTech Hydraulic/Electric Hybrid Data Recording and Telemetry</title>
<link href="tb_style.css" rel="stylesheet" type="text/css" media="screen" />
<asp:ContentPlaceHolder id="tb_HeaderPlaceHolder" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="tb_formBody" runat="server">
<!-- Begin wrapper -->
<div id="tb_wrapper">
<asp:Label ID="tb_lblFormsAuthenticationUserData" runat="server" Text="Nothing" Visible="false"></asp:Label>
<!-- Begin top -->
<div id="tb_top">
<ul id="tb_nav">
<asp:Label ID="tb_lblMasterMenu" runat="server"></asp:Label>
<li><asp:LoginStatus ID="tb_LoginStatus" runat="server" LogoutAction="Redirect" LogoutPageUrl="Logout.aspx" /></li>
</ul>
<div id="tb_Greeting">
<asp:LoginView ID="tb_MasterLoginView" runat="server">
<LoggedInTemplate>
Logged in as <asp:LoginName ID="MasterLoginName" runat="server" />
</LoggedInTemplate>
</asp:LoginView>
</div>
<asp:Label ID="test" runat="server"></asp:Label>
</div>
<!-- Begin content -->
<div id="tb_content">
<asp:ContentPlaceHolder id="tb_ContentPlaceHolder" runat="server">
</asp:ContentPlaceHolder>
</div>
<!-- End content -->
<!-- Begin footer -->
<div id="tb_footer"><div id="something">
<!-- Begin badges -->
<div>
<img src="http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0 Strict" height="31" width="88" /> <!-- HTML validation badge -->
<a href="http://jigsaw.w3.org/css-validator/check/referer">
<img style="border:0;width:88px;height:31px" src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!" /> <!-- CSS validation badge -->
</a>
</div></div>
<!-- End badges -->
</div>
<!-- End footer -->
</div>
<!-- End wrapper -->
</form>
</body>
</html>
EDIT2: I moved my Button outside of my label and manually set the button's visibility along with the label's visibility (that was the only reason I was using those labels in the first place), and it worked just fine. I just spent the last hour and a half trying to figure this out, so in case anyone else ever has the same issue again:
ASP:BUTTONs WILL NOT FIRE FROM INSIDE OF ASP:LABELs!!!!!
try butting this line in the page load
tb_btnAddUserSubmit.Click += new EventHandler(tb_btnAddUserSubmit_Click);
I think the problem may be that the click handler is not register in the click event
Have you copied this method from other page/application ? if yes then it will not work, So you need to delete the event and event name assigned to the button then go to design and go to button event properties go to onClick event double click next to it, it will generate event and it automatically assigns event name to the button. this should work
Try AutoEventWireup="false" in your page headers. I haven't worked in ASP.net in like 5 years but I remember that would sometimes break stuff.
I cannot find your tb_btnAddUserSubmit declaration in .cs code behind, and the handler.
You need to have a AddUser.Designer.cs class. Make sure to check that.
You also need to register the event in OnInit, instead of Page_load.

Ext.net MVC Razor Cell double click on gridpanel

I want to double click on a cell of a gridpanel an call another
action/view with extra parameter example:
The gridpanel is in .../Student and I want to show the details of one
student in another page ex: /Student/Detail/1 double clicking on his
name, id, or wherever data is on his record.
Sorry for the bad english
I tried this
#(
Html.X().GridPanel()
.Title("Students")
.Width(550)
.Height(200)
.ForceFit(true)
.Store(Html.X().Store().Model(Html.X().Model()
.Fields(fields =>
{
fields.Add(Html.X().ModelField().Name("StudentID"));
fields.Add(Html.X().ModelField().Name("LastName"));
fields.Add(Html.X().ModelField().Name("FirstMidName"));
fields.Add(Html.X().ModelField().Name("EnrollmentDate"));
}
)
).DataSource(Model)
).ColumnModel(
Html.X().Column().Text("Student ID").DataIndex("StudentID"),
Html.X().Column().Text("Last Name").DataIndex("LastName"),
Html.X().Column().Text("First Name").DataIndex("FirstMidName"),
Html.X().DateColumn().Text("Enrollment").DataIndex("EnrollmentDate")
).DirectEvents(de =>
{
de.CellDblClick.Url = "Edit"; // also tried
de.CellDblClick.Action = "Edit";
de.CellDblClick.ExtraParams.Add(1); //static
later I'll add the StudentID here
}
)
)
The gridpanel show the data without problem but when I doubleclick on a
cell this is the request that it's sended
localhost:10782/Student/Edit?_dc=1359052548829
instead of this
localhost:10782/Student/Edit/1
I can suggest to manage an URL with a Before handler.
To remove "?dc..." from an URL, please set up DisableCaching="false".
<%# Page Language="C#" %>
<%# Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Ext.NET v2 Example</title>
<script>
var counter = 1;
</script>
</head>
<body>
<ext:ResourceManager runat="server" />
<ext:Button runat="server" Text="Test">
<DirectEvents>
<Click Url="Some URL" Before="o.url = o.rawUrl + counter++;" DisableCaching="false">
<CustomConfig>
<ext:ConfigItem Name="rawUrl" Value="Controller/Action/" Mode="Value" />
</CustomConfig>
</Click>
</DirectEvents>
</ext:Button>
</body>
</html>

NameSpace Manager or XsltContent to parse aspx page

How can I use NameSpace Manager or XsltContent to parse aspx page?
I am using HtmlAgilityPack.
I am trying to parse aspx page to get Button and Label controls IDs. I am getting the following error when I try to select node with asp:Button element.
Here is the error message:
Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
string filePath = #"C:\webform4.aspx";
htmlDoc.Load(filePath);
foreach (HtmlNode div in htmlDoc.DocumentNode.SelectNodes("//div"))
{
Response.Write(div.Id);
foreach (HtmlNode asp in div.SelectNodes("asp:Button"))
{
Response.Write(asp.Id);
}
}
My aspx page looks as follows:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm4.aspx.cs" Inherits="WebApplication1.WebForm4" %>
<!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 id="mydiv">
<asp:Button ID="Button1" runat="server" Text="Button on page4" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label on page 4"></asp:Label>
<br />
<br />
<asp:Button ID="Button2" runat="server" Text="second button page 4" />
<br />
<asp:Button ID="Button3" runat="server" Text="second button page 4" />
</div>
</form>
</body>
</html>
I use Linq with the Agility Pack myself, rather than XPath, how about this?
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
string filePath = #"C:\webform4.aspx";
htmlDoc.Load( filePath );
var aspNodes = htmlDoc.DocumentNode.Descendants().Where( n => n.Name.StartsWith( "asp:" ) );
foreach ( var aspNode in aspNodes ) {
Console.WriteLine( "Element: {0} Id: {1}", aspNode.Name, aspNode.Attributes["Id"].Value );
}

Validating textbox using javascript in MasterPage

I am using javascript for customValidator to validate textboxes in ASP.Net.
The code works perfectly when I am using a normal page, but as soon as I put that inside a MasterPage, the code doesn't work.
Below is the code for my aspx page. If I put this code inside a MasterPage it doesn't work.
Could you guys advise me how to make this work inside a MasterPage
Thanks,
Abhi.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
function validateOrFields(source, args){
var sUser = document.getElementById('TextBox1');
if (sUser.value == "")
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
return;
}
<div>
<asp:TextBox ID="TextBox1"
runat="server"></asp:TextBox>
<asp:CustomValidator ID="FieldValidator"
runat="server"
Text="Enter either a user name"
ClientValidationFunction="validateOrFields" onservervalidate="FieldValidator_ServerValidate"/>
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
</body>
</html>
The problem is the ID of the TextBox. When placed in the Master Page, it gets a different ClientID.
var sUser = document.getElementById('<%= TextBox1.ClientID %>');
you need to get the id by using ClientID
Replace your code by
var sUser = document.getElementById('<%= TextBox1.ClientID %>');
Try document.getElementById('ct100_TextBox1').value. It is just a temporary fix!! But anyone please suggest how to get this ID dynamically using code. I got this by viewing source of the page generated. I have also posted the same question here
link text

Categories