get the Page's HiddenField Value in UserControl on Page - javascript

I want to read the Page(.aspx) Hiddenfield Value in the User Control that is placed on that Page and process some logic.
FOr eg: I have a hidden field x on a Page. The Page has many user controls and I want to access this hidden field (x) in those User Controls where value of x will be set by a Javascript in the Page.
I am trying to find the HiddenControl and read its value from codebehind of usercontrol(.ascx.cs) but always get null.
HiddenField colname = UIUtils.FindControlRecursive(this.Parent.Page, "MainContent_AssignedTo_ColName") as HiddenField;
The ID is same as the hiddenfield on client Side. I tried this.Parent and this.Parent.Parent for the first argument too but no luck.
what am I missing here.

Here is my aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestFindControl._Default" %>
<%# Register Src="ReadHiddenField.ascx" TagName="Assign" 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>
<asp:HiddenField ID="HiddenField1" runat="server" Value="10">
</asp:HiddenField>
<asp:placeholder ID="Placeholder1" runat="server"><uc1:Assign id="test" runat="server"></uc1:Assign> </asp:placeholder>
</div>
</form>
</body>
</html>
and here is my code behind on control:
protected void Page_Load(object sender, EventArgs e)
{
HiddenField test = (HiddenField)Page.FindControl("HiddenField1");
var j = test.Value;
}

Try:
HiddenField colname = (HiddenField)Page.FindControl("The id of control");

private void GetParentPageHiddenField()
{
System.Web.UI.WebControls.HiddenField ParenthiddenField = null;
Control ctl = this.Parent;
while (true)
{
ParenthiddenField = (System.Web.UI.WebControls.HiddenField)ctl.FindControl("ParentPageHiddenFieldID");
if (ParenthiddenField == null)
{
if (ctl.Parent == null)
{
return;
}
ctl = ctl.Parent;
continue;
}
break;
}
var parentHiddenFieldValue=ParenthiddenField.Value;
}

Related

ASP.Net Webform: Add HTML and javascript dynamically

I need a ASP.net application which is only kind of "pageDisplayer" from content which is coming from an API. So I choose ASP.net Webform and tried the following:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="PMLetterAcceptance.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:Literal runat="server" id="JavaScript"></asp:Literal>
</head>
<body>
<form id="letterform" runat="server">
<div>
<%= pageContent %>
</div>
</form>
</body>
public partial class WebForm1 : System.Web.UI.Page
{
protected string pageContent = "";
protected void Page_Load(object sender, EventArgs e)
{
...// here I fetch the html and javascript content from the API
dynamic json = Json.Decode(streamReader.ReadToEnd());
if (json.status != "OK")
pageContent = json.error;
else
pageContent = json.html;
JavaScript.Text = json.script;
}
}
The html content and the script are loaded correct but I cannot access DOM elements in the javascript. The javascript looks like that
(function()
{
function processForm(e)
{
... // Here I want to do some stuff before sending the form
}
let form = document.getElementById('letterform');
if (form.attachEvent)
form.attachEvent("submit", processForm);
else
form.addEventListener("submit", processForm);
})();
No I get the error "form is null". For me it looks like the javascript is executed before the DOM is ready. But how can I change this to make it work like expected?
Try putting the JS (literal) at the bottom of the page, before the closing body tag. That way, the HTML will be loaded before the JS tries to find elements.

Get value from html input text type textbox as string and pass it to C# hashtable being used in aspx

The textbox is defined as html input text type and takes input from the users. This value is needed to pass as key to hashtable defined in aspx.cs file being used in aspx file. But the correct value is not being given and an exception is being thrown. Any help in this regard would be helpful. Thanks
The code is as follows:
<% =Hashtable[document.getElementbyId("Textbox").Value]%>
document.getElementbyId("Textbox").Value is not giving the correct output. If it is replaced by a string value acting as key then it works fine. The only problem is getting the string value from textbox.
First include jquery in head section
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
Try below code to read textbox value :
First read text box value using
var key = $("[id$=Textbox]").val();
and see if value is present in texbox if present use this to read hash value
<% =Hashtable[key]%>
Try this it worked for me :
aspx :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function GetHashtable() {
alert("<% = hashtable[this.test] %>");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtKey" OnTextChanged="txtKey_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>
</div>
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</body>
</html>
Code behind :
public partial class _Default : System.Web.UI.Page
{
protected int test;
public Hashtable hashtable = new Hashtable();
static Hashtable sHashtable = new Hashtable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
sHashtable[1] = "One";
sHashtable[2] = "Two";
sHashtable[13] = "Thirteen";
}
}
protected void txtKey_TextChanged(object sender, EventArgs e)
{
test = Convert.ToInt32("0" + txtKey.Text);
hashtable = sHashtable;
Page.ClientScript.RegisterStartupScript(this.GetType(), "GetHashtable", "GetHashtable();", true);
}
}

`getJSON()` of jQuery not calling same page's function to get JSON data

I want to use getJSON()'s demo to show its use insetead of $.ajax.
I've till created the following code.
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Test_JSON.aspx.vb" Inherits="Test_HTML" %>
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test HTML</title>
<script src="Script/jquery-1.9.1.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter Name:
<asp:TextBox runat="server" ID="txtName"></asp:TextBox>
<asp:Button runat="server" ID="btnView" Text="View Label of Name" />
</div>
</form>
<script type="text/javascript">
function getJsonData() {
debugger;
$("#btnView").val = $("#txtName").val();
var objJson = {};
objJson["name"] = $("#txtName").val();
return objJson;
}
$("#btnView").click(function(event) {
debugger;
$.getJSON('/Test_JSON.aspx/getJsonData', function(result) {
debugger;
$('<p> APPEND TEXT </p>').appendTo('#btnView');
$('<p> PREPEND TEXT </p>').prependTo('#btnView');
});
});
</script>
</body>
</html>
VB code for PageMethod
Imports Newtonsoft.Json
Partial Class Test_HTML
Inherits System.Web.UI.Page
<Web.Services.WebMethod()> _
Public Shared Function getJsonData(ByVal name As String) As String
Dim jsonString As String = String.Empty
Dim dt_jsonData As New DataTable
Dim dr As DataRow = dt_jsonData.NewRow
Try
dt_jsonData.Columns.Add("name")
dr("name") = name.ToString.Trim()
dt_jsonData.Rows.Add(dr)
If dt_jsonData.Rows.Count <> 0 Then
jsonString = JsonConvert.SerializeObject(dt_jsonData)
End If
Catch ex As Exception
Return ""
Exit Function
End Try
Return jsonString
End Function
End Class
I want to get data from getJsonData(). But my getJSON() is not getting executed with URL. Is there any other way I should use this?
All I need to do is:
1> Enter text in text box
2> Click on button
3> Get textbox's value through getJSON() method and use it somewhere else.
4> And also use appendTo and prependTo methods for demo.

Register and execute a JavaScript function in a ASP.NET Page_Load event

How can I register AND execute that JavaScript function in ASP.NET on a Page_Load event so my textbox content gets validated and if nothing is in there I can disable a save button?
function Validate(source, arguments)
{
}
Use ClientScriptManager.RegisterStartupScript
See here for example
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
StringBuilder cstext1 = new StringBuilder();
cstext1.Append("<script type=text/javascript> alert('Hello World!') </");
cstext1.Append("script>");
cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>RegisterStartupScript</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Hope this helps

Force asp.net page postback from server

I have a page that is created entirely dynamically in the code behind (oh joy).
On pressing a button on this page, more elements are added to the page - which is fine, however, the refreshed page doesn't appear until the next postback. I would do a redirect, but I want to keep the state of any data entered in the existing controls.
So - I need to force a postback from the server code behind code. I imagine that this involves inserting some js code - but beyond that, I've not had any joy at all.
Here is an example to make things clearer:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
A very simple page.
The code behind is simple too:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["data"] = 1;
}
PopulatePage();
}
private void PopulatePage()
{
int data = (int)Session["data"];
for (int n = 0; n < data; ++n)
{
TextBox tb = new TextBox();
tb.ID = n.ToString();
PlaceHolder1.Controls.Add(tb);
Literal lit = new Literal();
lit.Text = "<br/>";
PlaceHolder1.Controls.Add(lit);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int data = (int)Session["data"];
Session["data"] = ++data;
}
}
You click the button and more controls are added. This is way simpler than the page that I am having issues with, but it demonstrates the problems that I am having.
The postback is not needed and is a bit of a hack, you would be better off fixing the problem at the root.
private void PopulatePage()
{
for (int n = 0; n < Counter; n++)
{
CreateSingleControl(n);
}
}
private void CreateSingleControl(int index)
{
TextBox tb = new TextBox();
tb.ID = String.Format("text{0}", index);
PlaceHolder1.Controls.Add(tb);
Literal lit = new Literal();
lit.Text = "<br/>";
PlaceHolder1.Controls.Add(lit);
}
protected override void CreateChildControls()
{
PopulatePage();
base.CreateChildControls();
}
protected void Button1_Click(object sender, EventArgs e) {
CreateSingleControl(Counter);
Counter++;
}
private int Counter
{
get
{
return Counter = (int)(ViewState["data"] ?? 1);
}
set
{
ViewState["data"] = value;
}
}
Use the Request forms list to search unique control ID's
Something like this link below, last post, not sure his code is exactly correct, but you'll get the idea.
Searching for controls in Request.Form / Parsing a NameValueCollection
Give your controls unique IDs' and you can search for them on the postback.
Plus, i use to add other things to the ID to let the postback searching know what type of control it was, like adding txt_firstname, i know that firstname was a txtbox. Use regex to search the returned strings.

Categories