I have setup a hiddenfield control and a linkbutton on an aspx Masterpages content page.
<asp:HiddenField ID="HiddenField1" runat="server" value='<%# Eval("ID") %>'/>
<asp:LinkButton ID="LinkButton1" runat="server" postbackurl="orderhistorydetail.aspx">View</asp:LinkButton>
When trying to retrieve the value on the postback page using this code...
string oid = Request.Form[HiddenField1];
I am getting the error...
The name 'HiddenField1' does not exist in the current context.
Is this because of materpages? How can I fix this?
EDITED...
I viewed the source html that was generated for the page that has the hiddenfield control on it and this was the output...
<input type="hidden" name="ctl00$MainContentPlaceHolder1$ListView1$ctrl0$ctl00$HiddenField1" id="MainContentPlaceHolder1_ListView1_ctrl0_HiddenField1_0" value="12386026" />
Now, as for the code you originally gave me, I updated it to this...
HiddenField hf = Page.PreviousPage.Master.FindControl("MainContentPlaceHolder1").FindControl("ListView1").FindControl("HiddenField1") as HiddenField;
Still no luck. Am I getting close?
The page you are posting to has no knowledge of the Controls that are present on the previous page. You need to use FindControl for that.
HiddenField hf = Page.PreviousPage.Master.FindControl("ContentPlaceHolder1").FindControl("HiddenField1") as HiddenField;
string oid = hf.Value;
Or if you really want to use Request.Form you need to use the UniqueID.
string oid = Request.Form[HiddenField1.UniqueID];
First you must find the PlaceHolder of the Page that is using a Master Page and then the correct Control within the PlaceHolder.
If you want to check what all the Posted values are, use this:
foreach (string s in Request.Form.Keys)
{
Response.Write(s.ToString() + ": " + Request.Form[s] + "<br>");
}
Related
I have a userControl being dynamically added to my form, anywhere from 1 to 20 times.
The control contains hyperlink field (visible) and a reference field (invisible). The problem is that the hyperlink is not passing the value of the reference field as linked page parameter.
The userControl coding looks like this:
<asp:Hyperlink ID="childLink" Enabled="true" DataNavigateUrlFields="aSeq"
DataNavigateUrlFormatString="~/Header.aspx?aSeq={0}" NavigateUrl="~/Header.aspx"
runat="server><%# DataBinder.Eval(Container, "DataItem.cName") %> </asp:HyperLink>
So, the hyperlink should open the Header page, passing the value of the "aSeq" field which looks like this:
<asp:HyperLink ID="aSeq" Enabled="true" DataNavigateUrlFields="aSeq" DataNavigateUrlFormatString="~/Header.aspx?aSeq={0}" NavigateUrl="~/Header.aspx"
runat="server"><%# DataBinder.Eval(Container,"DataItem.genePK") %></asp:HyperLink>
It does go to the page load for Header.aspx page, but the Request.QueryString["aSeq"] is always NULL. On the Page_Load I have a short block of code:
string aRequest = Request.QueryString["aSeq"];
if (aRequest==null)
{
PopulateHeader("GKEAAHDI");
}
else
{
PopulateHeader(aRequest);
}
I can only surmise it has not gotten the value of the field tagged "aSeq". I used a hyperlink because a textbox will not allow a code block for the databinder.
What have I done!?
According to MSDN " The value of the field specified by the DataTextField property is passed as a query string to a Web page specified in the format string." So you would need to add DataTextField="aSeq" in your asp:hyperlink declaration.
Not tested, just researched.
I need to hide /unhide the labels and textbox depending on db results , I tried something like this but it doesnt works, the condition should be like if the db field is empty for that field , then the label associated with that field should hidden (not visible) , following is the code i tried :
<asp:Label ID="lblBirth" Text="DOB:" runat="server" ViewStateMode="Disabled" CssClass="lbl" />
<asp:Label ID="DOB" runat="server" CssClass="lblResult" Visible='<%# Eval("Berth") == DBNull.Value %>'></asp:Label>
Code behind:
protected void showDetails(int makeID)
{// get all the details of the selected caravan and populate the empty fields
DataTable dt = new DataTable();
DataTableReader dtr = caravans.GetCaravanDetailsByMakeID(makeID);
while (dtr.Read())
{
//spec
string value = dtr["Price"].ToString();
lblModel.Text = dtr["model"].ToString();
birthResult.Text = dtr["Berth"].ToString(); }}
To make your aspx version work your control should be data bound to data source that contains "Berth" property. As I can see from code behind, you prefer to use c# to populate controls. In this case you may just do the following:
DOB.Visible = dtr["Berth"] == DBNull.Value;
I think that using data binding is more preferable solution.
I have the following client side code in .aspx page within a datalist itemtemplate that takes questions from the database like this:
<Itemtemplate>
<b> <%=GetQuestionNum()%>)
<%#Server.HtmlEncode(Eval("Text").ToString())%></b>
<br />
<asp:Panel ID="A" runat="server" Visible='<%#GetVisible(Eval("OptionA").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="A">
<%#Server.HtmlEncode(Eval("OptionA").ToString())%>
</option><br />
</asp:Panel>
<asp:Panel ID="B" runat="server" Visible='<%#GetVisible(Eval("OptionB").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="B">
<%#Server.HtmlEncode(Eval("OptionB").ToString())%>
</option><br />
</asp:Panel>
<asp:Panel ID="C" runat="server" Visible='<%#GetVisible(Eval("OptionC").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="C">
<%#Server.HtmlEncode(Eval("OptionC").ToString())%>
</option><br />
</asp:Panel>
<asp:Panel ID="D" runat="server" Visible='<%#GetVisible(Eval("OptionD").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="D">
<%#Server.HtmlEncode(Eval("OptionD").ToString())%>
</option><br />
</asp:Panel></itemtemplate>
The output is like:
1) What is your age group?
- Option 1
- Option 2
- Option 3
- Option 4
The ID's of the radio buttons are dynamic ("Q" & QuestionID). If there is no answer to a question then the GetVisible function returns false and the containing panel is hidden.
I have been trying to get rid of the html and replace these with asp:radiobuttons but it is not possible to set id's from databinding.. only simply. I was trying something like:
<asp:RadioButton ID="Q<%#Eval("ID")%>" runat="server" Visible='<%#GetVisible(Eval("OptionA").Tostring())%>'
Text='<%#Server.HtmlEncode(Eval("OptionA").ToString())%>' />
Here is the function that provides data:
Public Shared Function GetQuestionsForSurvey(ByVal id As Integer) As DataSet
Dim dsQuestions As DataSet = New DataSet()
Try
Using mConnection As New SqlConnection(Config.ConnectionString)
Dim mCommand As SqlCommand = New SqlCommand("sprocQuestionSelectList", mConnection)
mCommand.CommandType = CommandType.StoredProcedure
Dim myDataAdapter As SqlDataAdapter = New SqlDataAdapter()
myDataAdapter.SelectCommand = mCommand
mCommand.CommandType = CommandType.StoredProcedure
mCommand.Parameters.AddWithValue("#id", id)
myDataAdapter.Fill(dsQuestions)
mConnection.Close()
Return dsQuestions
End Using
Catch ex As Exception
Throw
End Try
End Function
but I'm finding it impossible to work with the html controls, i.e get their .text value from codebehind, or adding events!
Please can an expert suggest a better way to replace the html with suitable asp.net web controls or from the codebehind and output it. Or point me in the right direction?
Thanks :0)
I had some experience with ASP controls and data binding. The problem you are facing is probably the fact that once you declare a control via markup you can't access it from data binding. Also, you should not confuse the server-side ID with the client-side ID.
The server-side ID, mapped to Id property of controls, is used to programmatically access the control from code behind. Client-side ID is the ID that will be placed in tag's id attribute and is mapped to ClientId property.
Judging from your question, what you need is to build a multi-choice survey, and, in my opinion, it's not important how the IDs are generated, just that they are properly grouped for each question.
I'll answer the part of programmatically accessing controls in data binding, which is a part of your question.
Here is an example from my code. Suppose you have a very simple GridView like this
<asp:GridView ID="example" runat="server" OnRowDataBound="DataBound">
<Columns>
<asp:TemplateField HeaderText="New">
<ItemTemplate>
<asp:Image ID="imgExample" runat="server" />
</ItemTemplate>
</Columns>
</asp:GridView>
It takes a data set during data binding and sets the image according to some property. It works the same as DataList, don't worry.
Now, in code behind, you handle the RowDataBoundEvent. You can't access the imgExample object directly, because it's a child of the ItemTemplate. When the row is bound, you have direct access to the row and then you can use the FindControl method of Control class
Here is C# code example (easy to convert to VB)
protected void DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) //Required
{
GridViewRow row = e.Row;
[...] //get an email message
(row.Cells[0].FindControl("imgExample") as Image).ImageUrl = (email.AlreadyRead)
? "Mail_Small.png"
: "Mail_New_Small.png";
}
}
Application to your case
In order to build a multi-choice survey, my advice is to create a DataList that will hold questions (the outer control) and then, for each row, declare a RadioButtonList that holds answers (the inner control). Bind the outer data list to the data set of questions and answers. Handle the RowDataBound event or whatever it's called in the DataList world. When you handle that event, bind the inner radiobuttonlist to the answers.
It should work for you
I am actually working on something similar at the moment. I am using javascript and jQuery to dynamically add controls to my page. After adding them to my page I have to get the new controls, their text, etc. The way I've been doing it is something like this:
<table id='BuilderTable' class="BuilderTable">
<tbody class='BuilderBody'>
</tbody>
</table>
<asp:Button runat="server" ID="saveButton" OnClick="SaveButton_Click" OnClientClick="SaveData()"
Text="Save Form" />
<asp:HiddenField runat="server" ID="controlsData" />
This table is where I put all my new controls.
Then when the client clicks the save button it first calls this javascript / jQuery function:
function SaveData() {
var controlRows = $('#BuilderTable tr.control');
var controls= [];
controlRows.each(function (index) {
//process control information here ...
controlText = //use jQuery to get text, etc...
var control = {
Index: (index + 1),
Text: controlText
};
controls.push(control);
});
var str = JSON.stringify(questions);
$('#<%= controlsData.ClientID %>').val(str);
}
Then the server side function for the button click is called (this in in C#, adapt to VB).
protected void SaveButton_Click(object sender, EventArgs e)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
string str = controlsData.Value;
List<Control> controls = jss.Deserialize<List<Control>>(str);
}
Using a Control class like this:
public class Control
{
public int Index { get; set; }
public string Text { get; set; }
}
This code uses javascript and jQuery to get your controls, JSON to serialize the data and save it in a asp hiddenfield then grab the data server-side and deserialize into objects that your code can use. Then take the data and do whatever you need to.
I have a text box like this:
<asp:TextBox ID="txtLogin" runat="server" Text='<%# strUserID %>'></asp:TextBox>
strUserID is a string value set in my codebehind and I bind the textbox to see the value. I tried with <%= strUserID %>, but it doesnt work for me. can you please tell me why?
Also, I have a hidden field like this:
<input id="hdnUserID" runat="server" type="hidden" value='<%=txtLogin.ClientID %>' />
and I have a function prints the hidden field value like this:
function CheckForValue()
{
var uid = window.document.getElementById('<%= txtLogin.ClientID %>').value;
alert(hdnUserID);
return false;
}
But this alert always prints as "[object]". Can anyone please explain this? Looks like <%= value %> doesnt work at all. But I have seen in my earlier projects where the existing code has these kinda lines!!
If your strUserID value is a member variable set in the code behind make sure it's access modifier is declared as at least protected or you will not be able to access it. Also the notation you want to use is <%= strUserID %> not <%# strUserID %> # is used to get the value of a databound dataItem.
Also in your second point I dont see the need for your hidden field. Can you not just use the following to get your textbox value?
function CheckForValue()
{
var textValue = window.document.getElementById('<%= txtLogin.ClientID %>').value;
alert(textValue);
}
Try taking the innerHTML or innerText values of the textbox for your message.
I have an AutoCompleteExtender AjaxControlToolkit control inside a repeater and need to get a name and a value from the web service. The auto complete field needs to store the name and there is a hidden field that needs to store the value. When trying to do this outside of a repeater I normally have the event OnClientItemSelected call a javascript function similiar to
function GetItemId(source, eventArgs)
{
document.getElementById('<%= ddItemId.ClientID %>').value = eventArgs.get_value();
}
However since the value needs to be stored in a control in a repeater I need some other way for the javascript function to "get at" the component to store the value.
I've got some JavaScript that might help you. My ASP.Net AutoComplete extender is not in a repeater, but I've modified that code to detect the ID of the TextBox you are going to write the erturned ID to, it should work (but I haven't tested it all the way through to post back).
Use the value from 'source' parameter in the client side ItemSelected method. That is the ID of the calling AutoComplete extender. Just make sure that you assign an ID the hidden TextBox in the Repeater Item that is similar to the ID of the extender.
Something like this:
<asp:Repeater ID="RepeaterCompareItems" runat="server">
<ItemTemplate>
<ajaxToolkit:AutoCompleteExtender runat="server"
ID="ACE_Item"
TargetControlID="ACE_Item_Input"
...other properties...
OnClientItemSelected="ACEUpdate_RepeaterItems" />
<asp:TextBox ID="ACE_Item_Input" runat="server" />
<asp:TextBox ID="ACE_Item_IDValue" runat="server" style="display: none;" />
</ItemTemplate>
</asp:Repeater>
Then the JS method would look like this:
function ACEUpdate_CustomerEmail(source, eventArgs) {
UpdateTextBox = document.getElementById(source.get_id() + '_IDValue');
//alert('debug = ' + UserIDTextBox);
UpdateTextBox.value = eventArgs.get_value();
//alert('customer id = ' + UpdateTextBox.value);
}
There are extra alert method calls that you can uncomment for testing and remove for production. In a simple and incomplete test page, I got IDs that looked like this: RepeaterCompareItems_ctl06_ACE_Item_IDValue (for the text box to store the value) and RepeaterCompareItems_ctl07_ACE_Item (for the AC Extender) - yours may be a little different, but it looks practical.
Good Luck.
If I understand the problem correctly, you should be able to do what you normally do, but instead of embeding the ClientId, use the 'source' argument. That should allow you to get access to the control you want to update.
Since you are using a Repeater I suggest wiring the OnItemDataBound function...
<asp:Repeater id="rptResults" OnItemDataBound="FormatResults" runat="server">
<ItemTemplate>
<asp:PlaceHolder id="phResults" runat="server" />
</ItemTemplate>
</asp:Repeater>
Then in the code behind use something like
`Private Sub FormatResults(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
Dim dr As DataRow = CType(CType(e.Item.DataItem, DataRowView).Row, DataRow) 'gives you access to all the data being bound to the row ex. dr("ID").ToString
Dim ph As PlaceHolder = CType(e.Item.FindControl("phResults"), PlaceHolder)
' programmatically create AutoCompleteExtender && set properties
' programmatically create button that fires desired JavaScript
' use "ph.Controls.Add(ctrl) to add controls to PlaceHolder
End Sub`
Voila