In a follow up to my previous question, I want to get the value of the hidden input field from the child page codebehind.
I tried HtmlInputHidden hdnID = (HtmlInputHidden)Page.Master.FindControl("ctl00_hdnField");
but I get a "null" value.
A snippet of the Masterpage is:
<head runat="server">
<title>
<asp:ContentPlaceHolder ID="TitleContent" runat="server"></asp:ContentPlaceHolder>
<asp:Literal ID="Literal2" runat="server" Text=" : Logistics Management" />
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="~/css/styles.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="ScriptCssContent" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
......
......
......
<div id="container">
....
....
....
<div id="content" style="z-index:0;">
<asp:HiddenField ID="hdnField" runat="server" Value=""/>
....
....
....
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</div>
</div>
</form>
On my Child aspx page, I have this javascript block:
window.onload = function() {
var newDate = new Date();
var hidField = document.getElementById("ctl00_hdnField");
if (hidField != null)
hidField.value = newDate.toLocaleString();
}
When I "Add Watch" to
document.getElementById("ctl00_hdnField")
the value is correct.
Question: How would I access the value inside hdnField control, from codebehind?
So change it FROM
HtmlInputHidden hdnID = (HtmlInputHidden)Page.Master.FindControl("ctl00_hdnField");
TO
HiddenField hdnID = (HiddenField)Page.Master.FindControl("hdnField");
It's just a casting thing - notice HtmlInputHidden
changed to HiddenField
. You also don't need the ct100_
part - this is just so the HTML rendered element has a unique ID.
The control on your page is an asp.net control, not a generic HTML control.
You would use HtmlInputHidden
if you put a generic <input type="hidden" />
in your HTML.
You should create a property in Masterpage which wrap the HiddenField.
public String HdnFieldValue
{
get
{
return hidField.Value;
}
set
{
hidField.Value = value;
}
}
And in page code behind you can access it like this:
((YourCustomMaster)Page.Master).HdnFieldValue
If something is not clear please ask me.
I don't think you need to prefix the hidden field's ID with ctl00_
, just use the normal ID:
(HtmlInputHidden)Page.Master.FindControl("hdnField");
Use something like:
if (Page.Master.FindControl("hdnField") != null)
{
String myValue = (HtmlInputHidden)Page.Master.FindControl("hdnField").value;
}
来源:https://stackoverflow.com/questions/15689859/accessing-value-of-a-hidden-field-on-masterpage-from-codebehind