How to access Hidden Field of Parent page from child page - c#

In my ASP.NET main page I have one hidden field and and one button. When the user clicks the button I am showing the pop up (child page). I need to access a Hidden field while the pop up is loading. How could I access the Hidden field using c#?

Well, you can pass the value of the hidden field to the query string of the pop up. Something like this:
<asp:button id="ButtonInMainPage" runat="server" onclick="Popup();return false;" />
<asp:hidden id="hiddenValue" runat="server" />
<script type="text/javascript">
function Popup()
{
window.open('Child.aspx?hiddenValue='+document.getElementById('<%=hiddenValue.ClientID%>').value);
}
In child page_load:
string hiddenValue = Request.QueryString["hiddenValue"];
What I show is simple code, you must add necessary check or other according to your project.

This is your question:
In main page, there is a gridview, which contains a checkbox column, when a checkbox of a row is selected, add the corresponding ID to a hidden field. When user clicks the popup button, a window will be opened and the selected IDs will be passed to the new window. The question is the IDs are too long to pass in the query string.
My solution:
I think you can remove the hidden field, and remove all client scripts of your popup button.
<asp:button id="PopupButton" runat="server" Text="Click to pop up" />
Add a server event of the button, like:
void PopupButton_Onclick(object sender, EventArgs e)
{
string IDs = CollectTheSelectedIDsInTheGridView();
Session["IDs"] = IDs;
string js = #"<script type='text/javascript'>
window.open('Child.aspx');
</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(),"showChild",js);
}
EDIT
Your data list must look like this:
<table>
<asp:Repeater ID="myData" runat="server">
<ItemTemplate>
<tr>
<td><asp:CheckBox ID="selectedFlag" runat="server" Checked=<%# Eval("Checked") %> /></td>
<td><asp:Label ID="dataText" runat="server" Text=<%# Eval("TextData") %>></asp:Label></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>

Related

How to implement a click event on textbox in ASP.NET?

In my web application I need a functionality so that when users click on textbox to input values, it should make the button and the other fields visible?
I am using the code provided below but, could not get it working.
C#:
protected void TextBox1_Click(object sender, EventArgs e)
{
ButtonSearch.Visible = true;
}
ASP.NET:
<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged" OnClick="TextBox1_Click"></asp:TextBox>
<asp:Button ID="ButtonSearch" runat="server" OnClick="ButtonSearch_Click" Text="Search" Visible="False" />
How to accomplish this?
Set AutoPostback="True". This way the event will be fired server-side, and the button will become visible.
<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged" OnClick="TextBox1_Click" AutoPostBack="true"></asp:TextBox>
However, if you only want to toogle visility of a button, you really should considerate javascript. This will save a trip back to the server.
<asp:TextBox onclick="txtBox1_ClientClicked()" ID="TextBox1" runat="server" OnClick="TextBox1_Click"></asp:TextBox>
<asp:Button ID="ButtonSearch" runat="server" OnClick="ButtonSearch_Click" Text="Search" style="display:none;" />
<script type="text/javascript">
function txtBox1_ClientClicked(){
var theButton = document.getElementById('<%=ButtonSearch.ClientID%>');
theButton.style.display = 'block';
}
</script>
You do not need to post back to the server to accomplish your job. You can use client side onFocus event and javascript/jquery, for example.
I know I used an input of type text, and you are using an ASP Control which posts on server, but here is a JSFiddle to get you on the right track: http://jsfiddle.net/Mmjtz/1/
$("<%= ButtonSearch.ClientID %>").click(function(){
$("#TextBox1").show():
});
In this code you need to pass fields ID which you want to visible on the click of button.
Put the textbox inside a div and use the div's onClick event from codebehind. It's not what you asked but it works for me without any errors. Here is a javascript function to implement requested event:
function toggleVisibility()
{
document.getElementById('TextBox1').disabled = true;
/*
...some other code...
*/
}
And of course, you have to define your onclick event at the div definition after implementing this JS function.
<div id="TBdiv" onClick="toggleVisibility()">
<asp:TextBox ID="TextBox1"..../>
</div>
IMPORTANT: Since you now disabled your TextBox from codebehind, you have to enable it in somewhere before you want to use it again. Otherwise you will not see it while the page is running.
jQuery is the perfect solution for your problem. The code would be something like this:
$("#TextBox1").on("click",function(){$("#ButtonSearch").css("visibility", "visible");})
You include the script by adding <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> to the page and then you can add the piece of code above to within <script></script> tags.

How to avoid post-back of Check Box inside repeater

I am newbie for asp.net,
I have a repeater which contains check box,whenever I check the check box I am firing an event on checkchanged,but the page postbacks.
I have an update panel for the entire content in my page,but still postback occurs.Is there anyway to avoid postback.
(Ps:To avoid Postback,I am meaning to avoid the flicker that occurs)
Thanks
<asp:Repeater ID="rptrDepartment" runat="server" OnItemCommand="rptrDepartment_ItemCommand"
OnItemDataBound="rptrdepartment_databound">
<ItemTemplate>
<tr>
<td>
<asp:CheckBox ID ="chkRow" runat="server" OnCheckedChanged="ChkRow_ChkChanged" AutoPostback="true" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
And in my .cs page,
protected void ChkRow_ChkChanged(object sender, EventArgs e)
{
//some method
}
Just keep your repeater inside update panel rather than entire page, if you want some other controls also need partial postback then you can go for multiple update panels.

checkbox updated in realtime to table in DB

Was using a repeater to display a list on screen. For each record I added a <asp:checkbox, which I would like updated in real time to the corresponding table in the DB, depending on whether or not it was clicked.....So far I got: (Using JS)
ASPX:
<th style="width:200px;"><asp:CheckBox Name='<%# CallUtilityChangeId((int)Eval("id")) %>' runat="server"
onclick='UtilityChanged(<%#((int)Eval("id"))%>);'
Checked='<%# Convert.ToBoolean(Eval("Checked")) %>'/></th>
<th style="width:200px;"><%# Eval("Comment") %></th>
C#
protected string CallUtilityChangeId(int id)
{
return "Utilitychanged('" + id.ToString() + "');";
}
JavaScript:
function UtilityChanged(id) {
userId = userIdentifier;
}
The source code returns:
<th style="width:200px;">
<span Name="Utilitychanged('55');">
<input id="ctl00_ContentPlaceHolder1_rptSelectedUtilities_ctl01_ctl00" type="checkbox" name="ctl00$ContentPlaceHolder1$rptSelectedUtilities$ctl01$ctl00" onclick="UtilityChanged(<%#((int)Eval("id"))%>);" />
</span></th>
<th style="width:200px;"></th>
Instead of onclick="UtilityChanged(<%#((int)Eval("id"))%>);" />
I need it to return UtilityChanged("71") for eg. just the identification no. of the id.
Correct me if I'm wrong, but it sounds like you want to have a checkbox in a repeater that has a server sided event, where you can get an ID value to use in a database command, all done asynchronously? If so, you can use the update panels to do this.
First, you must wrap your repeater in an update panel and add a script manager:
<asp:UpdatePanel ID="UpdatePanel4" runat="server" >
<ContentTemplate>
<!-- put repeater in here -->
</ContentTemplate>
</asp:UpdatePanel>
Next, you want to add a checkbox with a server event attached to it. this gets added to the repeater row. You also want to add a label that has the ID value. In this example, its added by the data source
<ItemTemplate>
<tr class="listcolor">
<td style="display:none;border-right:0px solid #808080 ; border-bottom:0px solid #808080;">
<asp:CheckBox ID="myCB" Text="Approved" runat="server" AutoPostBack="true" OnCheckedChanged="check_change" />
</td>
<td style="display:none;border-right:0px solid #808080 ; border-bottom:0px solid #808080;">
<asp:label ID="userId" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "someId") %>'></asp:label>
</td>
</tr>
</ItemTemplate>
Now, add the check box event. When a control posts back to the server, if its in a repeater, or similar control, you can cast sender to the object that caused the postback, then get its parent row, then find the label control:
Protected Sub check_change(ByVal sender As Object, ByVal e As EventArgs)
'first, cast the sender to a check box
Dim cb As CheckBox = CType(sender, CheckBox)
'then use that to find the label in its parent control ( the row its on)
Dim userId As Label = CType(cb.Parent.FindControl("userId"), Label)
End Sub
That should do it. If you have any questions, let me know.
(without using page refresh) means using Ajax.
First you should understand how .Net server control is parsed into normal HTML tags.
Suppose your code is like this:
<asp:Repeater Id="rpt">
......
<asp:CheckBox ID="chkBox" runat="server" Name="someName" Checked="true" />
....
</asp:Repeater>
it 'll be rendered like this:
<span name="someName">
<input id="rpt_ctl00_chkBox" type="checkbox" name="rpt$ctl00$chkBox" checked="checked">
</span>
as you can notice there are 2 things here::
The checkbox is contained inside <span> tag.
The ID and Name properties of that checkbox is renamed by the .Net with something relative to the parent container(the Repeater) "RepeaterId_ct100_CheckBoxId".
Second thing if you want to get some value without been messed by the view engine or the .Net try to use custom attribute.
sorry for long introduction.
solution::
<input id="chkBox" runat="server" type="checkbox" checked='<%# Eval("Your_Record_ColumnName")%>' onchange="YourJavascriptFunctionName(this);return false;" columId='<%# Eval("Column_Id")%>'/>
Then by JavaScript or jQuery you get the value of that attribute.
function YourJavascriptFunctionName(chk)
{
recordId = $(chk).attr("columId");
//then use ajax to update the DB Table.
}
how to make ajax call that's another thing..tell me if you need help in it.

Setting a session variable before AutoPostBack fires in an asp:Button

How would I go about setting a session variable from the click of an ASP:Button before an AutoPostBack event fires.
Here is what I have right now, but I'm not exactly sure I'm doing this right:
<asp:Button ID="CommitBTN" runat="server" PostBackUrl="~/MMR_Home.aspx"
onclick="CommitBTN_Click" UseSubmitBehavior="true"
OnClientClick='<% string temp1 = "true"; Session["ClickedFlag"] = temp1; %>' Text="Commit Changes to Database" />
Would this be the correct way of performing this action or am I going at it completely wrong?
EDIT:
Changed my button tag to this:
<asp:Button ID="CommitBTN" runat="server" PostBackUrl="~/MMR_Home.aspx"
onclick="CommitBTN_Click" OnClientClick="document.getElementById('<%= Hidden.ClientID
%>').value='1'" UseSubmitBehavior="true" Text="Commit Changes to Database" />
I receive this as my error:
Microsoft JScript runtime error: Unable to set value of the property 'value': object is null or undefined
Use this:
Inside aspx file:
<form runat="server">
<asp:Button ID="CommitBTN" runat="server" Text="Button" onclick="CommitBTN_Click" OnClientClick="document.getElementById('HiddenField').value='Ram'"/>
<asp:HiddenField ID="HiddenField" runat="server" />
</form>
Or
<script type="text/javascript">
function setMyHiddenField(myValue) {
document.getElementById('HiddenField').value = myValue;
}
</script>
<form runat="server">
<asp:Button ID="CommitBTN" runat="server" Text="Button" onclick="CommitBTN_Click" OnClientClick="setMyHiddenField('Ram')"/>
<asp:HiddenField ID="HiddenField" runat="server" />
==================================================================
Inside aspx.cs file
protected void CommitBTN_Click(object sender, EventArgs e)
{
Session["ClickedFlag"] = HiddenField.Value;
Response.Write(Session["ClickedFlag"]);
}
It is easy to replase "Ram" with your value. ;)
you can change Ram to temp1 easy:
setMyHiddenField('temp1')
Or you can call this function on your another control events befor CommitBTN pressed
Use a Hidden Field control.
Update the Hidden Field to 1 on Button Client Click.
Update the Session Value in the Page Load' event. The Value will be 1 then update the Session variable and set theHidden Fieldvalue to 0 underneath theSession Variable` Update.
Reason for the Usage of Page Load event is that on clicking the Button as per the page life cycle the page events like PreInit, Init, InitComplete, PreLoad, Load executes before the execution of Button Control.
Page events execution takes place like below..
Preinit
Init
InitComplete
PreLoad
Load
Control Event
Load Complete
Pre Render
Hope this will help you...

Triggering a postback from Javascript fails

I am trying to trigger a postback if a certain condition is true. Initially, a user will click on a button on my form, the server does some work, and in the process of doing that work it assigns a hidden field the value of '1'. When the page reloads after that very first postback, I am trying to use javascript to check the hidden field, and if it is '1' I need the page to postback again so the server side can do some additional processing. The reason for doing it this roundabout way is so that I can create controls on the form from my C# code behind as well as download a file in 1 user interaction. Here is what I have so far:
<script type="text/javascript" language="JavaScript">
function atload() {
var HWInfo = document.getElementById('HiddenHW').value;
if (HWInfo == '1') {
alert("flag has been set");
__doPostBack('<%= hdnHidden.UniqueID %>', '');
}
}
$(document).ready(atload);
</script>
The alert that says the flag has been set correctly fires, but the __doPostBack does not. In my ASPX file, here is the relevant part:
<form id="InventoryForm" runat="server">
<div>
<asp:Label ID="lblClientList" runat="server" Text="Client List"></asp:Label>
<asp:DropDownList ID="comboClientList" runat="server"></asp:DropDownList>
<asp:Label ID="spacer1" runat="server" Text=" "></asp:Label>
<asp:Button ID="btnGenerateHWReport" runat="server" Text="Generate Hardware Inventory Report" />
<asp:Label ID="spacer2" runat="server" Text=" "></asp:Label>
<asp:Button ID="btnGenerateSWReport" runat="server" Text="Generate Software Inventory Report" />
<br />
<br />
<asp:Panel ID="MissingCompPanel" runat="server"></asp:Panel>
<asp:HiddenField ID="HiddenHW" runat="server" Value="0" />
<asp:HiddenField ID="hdnHidden" runat="server" />
</div>
</form>
I can tell the postback never fires, because I have breakpoints in the Page_Load C# codebehind that never get tripped. I have break points on almost every single line of this:
if (!Page.IsPostBack)
{
// Page is not a postback, this is the first visit here
string foo = HiddenHW.Value;
}
else
{
// Page is a postback and not initial load
string foo = HiddenHW.Value;
}
Why is my __doPostBak after the alert not firing, and is there a better way to do this? The end result I want is if my hidden field is '1', then I want my 2nd trip to the server to 1) actually happen and 2) know that the hidden field is '1' and not its default '0'.
Thanks!
how about just clicking the submit button programatically and have it call __doPostBack the way it normally does?
Try invoking the __doPostBack method on the page instead of the hidden control
__doPostBack('__Page', '');
When you get the value of HiddenHW, you're not using the right ID. If you look at the rendered source, the ID of the control is something like ctl00_HiddenHW. To get that ID, you should use HiddenHW.ClientID. I believe __doPostBack also needs the ClientID, not UniqueID.
function atload() {
var HWInfo = document.getElementById('<%= HiddenHW.ClientID %>').value;
if (HWInfo == '1') {
alert("flag has been set");
__doPostBack('<%= hdnHidden.ClientID %>', '');
}
}

Categories