Set the style of a parent DIV to a usercontrol - asp.net

I have a dynamically named DIV in a GridView which contains a user control with a dynamically assigned Parent_ID. The javascript is used to show or hide the DIV. I'll show you two examples of different rows without the ASP code.
Row 1 showing for Order # 123456:
<a href="<%#"javascript:collapseExpand('Order_Notes_Panel123456');" %>" >+</a>
<div id='Order_Notes_Panel123456' style="display:none;">
<uc:Comments_Control id="Comments_Control_ID" runat="server" Parent_ID='123456'/>
</div>
Row 2 showing for Order # 678901:
<a href="<%#"javascript:collapseExpand('Order_Notes_Panel678901');" %>" >+</a>
<div id='Order_Notes_Panel678901' style="display:none;">
<uc:Comments_Control id="Comments_Control_ID" runat="server" Parent_ID='678901'/>
</div>
The good news is that the user control binds and works perfectly. The javascript shows (sets the style to "display:block;") and hides (style set to "display:none;") the appropriate DIV each time the '+' is clicked.
Here is my problem: there is a 'Reply' link in the user control that, when clicked, does a post-back and puts the control into Edit mode. When I employ this user control on another page without a containing DIV, you won't notice a thing. However, when the 'Reply' does its post-back, the containing DIV reverts back to style="display:none;".
Can you provide a recommendation how to set the parent DIV's style to "display:block;" while a user is obviously working with it? I would imagine the appropriate code would go in the code behind of the user control when it goes into Edit mode.
Thanks,
Rob
Update: I recognize that there is no runat=server in my DIV. Since I'm trying to establish a dynamic ID for each, I get an error if I try to use the runat. That is probably the reason why I can't reach it from code behind...

I am very happy of myself... (see the YouTube video for this phrase, you'll be glad you did.)
In summary, this is what I added:
1. New Javascript function to add the name of the target DIV to a hidden field (The "collapseExpand" function is in the Site.Master. I couldn't put "load_div_to_hidden" in the Site.Master since "myhiddenField" isn't set up on every page
2. New hidden field to capture the name of the target DIV
3. New Javascript function to run on window.onload, check if we've got a post-back, and then display the value from the hidden field
4. Adding second Javascript call from the href in the link
Below are the new snippets of code:
<script type="text/javascript">
function load_div_to_hidden(obj) {
var hidden = document.getElementById('<%= myhiddenField.ClientID %>');
hidden.value = obj;
}
function windowOnLoad() {
var isPostBack = (('<%= IsPostBack %>').toLowerCase() == 'true') ? true : false;
if (isPostBack == true) {
var hid_field_value = document.getElementById('<%= myhiddenField.ClientID %>').value;
var right_div = document.getElementById(hid_field_value);
right_div.style.display = "block";
}
}
window.onload = windowOnLoad;
</script>
<input type="hidden" id="myhiddenField" runat="server" value="" />
<a href="<%#"javascript:collapseExpand('Order_Notes_Panel123456'); javascript:load_div_to_hidden('Order_Notes_Panel123456');" %>" >+</a>
<div id='Order_Notes_Panel123456' style="display:none;">
<uc:Comments_Control id="Comments_Control_ID" runat="server" Parent_ID='123456'/>
</div>
Works like a charm!

Related

Can I get control from page placed in a frame of another page?

I am a desktop client developer. I now got to continue this project is ASP.NET with AJAX, so I am learning web development the hard way.
I need to get a list of all check boxes and their states from repeater control on Summary.aspx when user clicks button CmdSave on ChoicePage.aspx.
Can I subscribe to event CmdSave_Click() in Summary.aspx or is there some way to approach Summary.aspx's repeater control from ChoicePage.aspx?
(MSDN talks about passing values from page to page in this article but this doesn't help me)
Here is the problem:
Page ChoicePage.aspx is included in Master AppMaster.master page. ChoicePage has Content tag which includes CmdSave and it's event handler CmdSave_Click() and it also includes iframe tag for displaying another page, Summary.aspx
On Summary.aspx I have repeater control which is bound to DataSource and relevant fields are of type bool represented by column of editable check boxes. Clicking these checkboxes mustn't cause Summary.aspx to refresh so I am not looking to handle (server-side) CheckedChanged event.
I am not sure if any code example would help here since this is more a concept question
function SetFrameStatus() {
var v = hdCommand.value.toString().toLowerCase();
hdCommand.value = "";
var frms = (GetFrameAll("FrameSummary"));
if (frms)
{ }
else return;
FrameSummary = frms[0];
DivSummary = FrameSummary.parentNode;
var FrameWindow = frms[1];
var FrameDocument = frms[2];
if (v == "showsummary") {
FrameWindow.location.replace(SummaryPageName);
}
}
<asp:Content ID="ContentSummary" ContentPlaceHolderID="NoUpdateDiv" runat="server">
<div id="DivMenu" class="Flat" style="overflow:visible; display:none;position:absolute;">
<input type="button" id="CmdSave" value="Save" onclick="CmdSave_Click()" />
</div>
<div id="DivSummary" style="position:absolute;margin:0px;padding:0px;display:none">
<iframe title="Loading" id="FrameSummary" marginheight="0px" marginwidth="0px" scrolling="auto"
style="padding:0px; margin:0px;width:auto;" src="loading.htm?Redirect=Summary.aspx" frameborder="0"
onload="FrameSummary_Load()"
></iframe>
</div>
In the end this is what solved my problem:
On ChoicePage.aspx in CmdSave_Click() function I called another function on Summary.aspx.
This other function did __dopostback("Repeater", "") and on Render event in my code behind I iterate through a Repeater.
I am leaving this question unanswered because I am sure there is a better way to do this.

JQuery with dynamic content

If I had a div tag inside a repeater, and i want to add a jquery effect to every one of those div tags, how would that be done?
<script type="text/javascript">
$(function() {
//run the currently selected effect
function runEffect() {
//most effect types need no options passed by default
var options = {};
//check if it's scale, transfer, or size - they need options
//if (selectedEffect == 'scale') { options = { percent: 0 }; }
//run the effect
$("#effect").effect('explode', options, 500, callback);
};
//callback function to bring a hidden box back
function callback() {
setTimeout(function() {
$("#effect:hidden").removeAttr('style').hide().fadeIn();
}, 1000);
};
//set effect from select menu value
$(document).ready(function() {
$("div.effect").click(function() {
runEffect();
return false;
});
});
});
</script>
<asp:Repeater ID="repItems" runat="server">
<ItemTemplate>
<div class="toggler">
<div id="effect" class="ui-widget-content ui-corner-all">
<h3 class="ui-widget-header ui-corner-all"><%#Eval("Tag") %></h3>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
I tried the above, but only the first div works. What am i doing wrong??
try using a class for those divs like:
<div id="effect" class="effect ui-widget-content ui-corner-all">
and in jquery use ("div.effect") selector.
i "think" that using the same id for multiple things might cause the issue...
The id values on HTML elements are required to be unique across the entire document. You're using the same id value for each item that that repeater displays, in violation of that rule. Now, the web being what it is, your browser doesn't complain about that, but try running your rendered HTML through a validator. jQuery only acts on the first such element, because it expects there to be only one.
If you switch from id to class, you should have much better results.
another idea to consider is to put a div tag with an id AROUND the repeater. the repeater itself looks pretty straightforward and looking at your jquery, it doesn't appear that it matters which of the div tags in the repeater is clicked.
$(document).ready(function() {
$("#base").click(function() {
runEffect();
return false;
});
});
<div id="base">
<asp:Repeater ID="repItems" runat="server">
<ItemTemplate>
<div class="toggler">
<div id="effect" class="ui-widget-content ui-corner-all">
<h3 class="ui-widget-header ui-corner-all"><%#Eval("Tag") %></h3>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
I think what you need to change is in the 'ready' function where you attach the click event - you are using $('div.effect') as the selector, which does not look valid to me. I suggest using $('.ui-widget-content'). This selects based on the class, rather than the id (which should be unique as noted by others).
If you're not wanting to use a class on those divs nested in your repeater, you can use partial ID matching. Even though the repeater will add information to beginning of your ID for each div (to ensure it's unique), the ID will still end in "effect", or whatever name you've used.
You can use this to your advantage. In your jQuery code, where you're operating on the "effect" ID, change your code from this:
$("#effect")
to this:
$("[id$='effect']")
This will select all elements whose ID END in "effect", so when repeater renames the ID of each div to "repItems_ ctl001_ effect" or what have you, jQuery will still find it.
Also do note, toward the end of your jQuery code listed in your question, you're attempting to access a div based on the class "effect", instead of the ID. Just an FYI.

Show hide div using codebehind

I have a DropDownList for which I am trying to show a div OnSelectedIndexChanged but it says OBJECT REQUIRED.
I am binding the DataList in that div:
aspx:
<asp:DropDownList runat="server" ID="lstFilePrefix1" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" >
<asp:ListItem Text="Prefix1" Value="Prefix1" />
<asp:ListItem Text="Prefix2" Value="Prefix2" />
<asp:ListItem Text="Prefix3" Value="Prefix3" />
<asp:ListItem Text="Prefix1 and Prefix2" Value="Prefix1 and Prefix2" />
<asp:ListItem Text="Prefix2 and Prefix3" Value="Prefix2 and Prefix3" />
</asp:DropDownList>
<asp:DataList ID="DataList1" runat="server" RepeatColumns="4"
CssClass="datalist1" OnItemDataBound="SOMENAMEItemBound"
CellSpacing="6" onselectedindexchanged="DataList1_SelectedIndexChanged"
HorizontalAlign="Center" Width="500px">
code behind:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstFilePrefix1.SelectedItem.Text=="Prefix2")
{
int TotalRows = this.BindList(1);
this.Prepare_Pager(TotalRows);
Page.ClientScript.RegisterClientScriptBlock(GetType(), "JScript1", "ShowDiv('data');", true);
}
}
javascript:
function ShowDiv(obj)
{
var dataDiv = document.getElementById(obj);
dataDiv.style.display = "block";
}
What am I doing wrong?
You can use a standard ASP.NET Panel and then set it's visible property in your code behind.
<asp:Panel ID="Panel1" runat="server" visible="false" />
To show panel in codebehind:
Panel1.Visible = true;
Make the div
runat="server"
and do
if (lstFilePrefix1.SelectedValue=="Prefix2")
{
int TotalRows = this.BindList(1);
this.Prepare_Pager(TotalRows);
data.Style["display"] = "block";
}
Your method isn't working because the javascript is being rendered in the top of the body tag, before the div is rendered. You'd have to include code to tell the javascript to wait for the DOM to be completely ready to take on your request, which would probably be easiest to do with jQuery.
There are a few ways to handle rendering/showing controls on the page and you should take note to what happens with each method.
Rendering and Visibility
There are some instances where elements on your page don't need to be rendered for the user because of some type of logic or database value. In this case, you can prevent rendering (creating the control on the returned web page) altogether. You would want to do this if the control doesn't need to be shown later on the client side because no matter what, the user viewing the page never needs to see it.
Any controls or elements can have their visibility set from the server side. If it is a plain old html element, you just need to set the runat attribute value to server on the markup page.
<div id="myDiv" runat="server"></div>
The decision to render the div or not can now be done in the code behind class like so:
myDiv.Visible = someConditionalBool;
If set to true, it will be rendered on the page and if it's false it won't be rendered at all, not even hidden.
Client Side Hiding
Hiding an element is done on the client side only. Meaning, it's rendered but it has a display CSS style set on it which instructs your browser to not show it to the user. This is beneficial when you want to hide/show things based on user input. It's important to know that the element CAN be hidden on the server side too as long as the element/control has runat=server set just as I explained in the previous example.
Hiding in the Code Behind Class
To hide an element that you want rendered to the page but hidden is another simple single line of code:
myDiv.Style["display"] = "none";
If you have a need to remove the display style server side, it can be done by removing the display style, or setting it to a different value like inline or block (values described here).
myDiv.Style.Remove("display");
// -- or --
myDiv.Style["display"] = "inline";
Hiding on the Client Side with javascript
Using plain old javascript, you can easily hide the same element in this manner
var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";
// then to show again
myDivElem.style.display = "";
jQuery makes hiding elements a little simpler if you prefer to use jQuery:
var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();
// ... and to show
myDiv.show();
Another method (which it appears no-one has mentioned thus far), is to add an additional KeyValue pair to the element's Style array. i.e
Div.Style.Add("display", "none");
This has the added benefit of merely hiding the element, rather than preventing it from being written to the DOM to begin with - unlike the "Visible" property. i.e.
Div.Visible = false
results in the div never being written to the DOM.
Edit: This should be done in the 'code-behind', I.e. The *.aspx.cs file.
<div id="OK1" runat="server" style ="display:none" >
<asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
</div>
vb.net code
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex = 0 Then
OK1.Style.Add("display", "none")
Else
OK1.Style.Add("display", "block")
End If
End Sub
RegisteredClientScriptBlock adds the script at the top of the page on the post-back with no assurance about the order, meaning that either the call is being injected after the function declaration (your js file with the function is inlined after your call) or when the script tries to execute the div is probably not there yet 'cause the page is still rendering. A good idea is probably to simulate the two scenarios I described above on firebug and see if you get similar errors.
My guess is this would work if you append the script at the bottom of the page with RegisterStartupScript - worth a shot at least.
Anyway, as an alternative solution if you add the runat="server" attribute to the div you will be able to access it by its id in the codebehind (without reverting to js - how cool that might be), and make it disappear like this:
data.visible = false
I was having a problem where setting element.Visible = true in my code behind wasn't having any effect on the actual screen. The solution for me was to wrap the area of my page where I wanted to show the div in an ASP UpdatePanel, which is used to cause partial screen updates.
http://msdn.microsoft.com/en-us/library/bb399001.aspx
Having the element runat=server gave me access to it from the codebehind, and placing it in the UpdatePanel let it actually be updated on the screen.
Hiding on the Client Side with javascript
Using plain old javascript, you can easily hide the same element in this manner:
var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";
Then to show again:
myDivElem.style.display = "";
jQuery makes hiding elements a little simpler if you prefer to use jQuery:
var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();
... and to show:
myDiv.show();

Access an asp:hiddenfield control in JavaScript

What is the best way to access an ASP.NET HiddenField control that is embedded in an ASP.NET PlaceHolder control through JavaScript? The Visible attribute is set to false in the initial page load and can changed via an AJAX callback.
Here is my current source code:
<script language="javascript" type="text/javascript">
function AccessMyHiddenField()
{
var HiddenValue = document.getElementById("<%= MyHiddenField.ClientID %>").value;
//do my thing thing.....
}
</script>
<asp:PlaceHolder ID="MyPlaceHolder" runat="server" Visible="false">
<asp:HiddenField ID="MyHiddenField" runat="server" />
</asp:PlaceHolder>
EDIT: How do I set the style for a div tag in the ascx code behind in C#? This is the description from the code behind: CssStyleCollection HtmlControl.Style
UPDATE: I replaced the asp:hiddenfield with an asp:label and I am getting an "undefined" when I display the HiddenValue variable in a alert box. How would I resolve this.
UPDATE 2: I went ahead and refactored the code, I replaced the hidden field control with a text box control and set the style to "display: none;". I also removed the JavaScript function (it was used by a CustomValidator control) and replaced it with a RequiredFieldValidator control.
My understanding is if you set controls.Visible = false during initial page load, it doesn't get rendered in the client response.
My suggestion to solve your problem is
Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server side. Use div, without runat=server. You can always controls the visiblity of that div using css.
If you need to add controls dynamically later, use placeholder, but don't set visible = false. Placeholder won't have any display anyway, Set the visibility of that placeholder using css. Here's how to do it programmactically :
placeholderId.Attributes["style"] = "display:none";
Anyway, as other have stated, your problems occurs because once you set control.visible = false, it doesn't get rendered in the client response.
If the Visibility is set to false server-side, the placeholder won't be rendered and you won't be able to access anything inside it from JavaScript. Your code should work when the placeholder is visible="true"
Get rid of the placeholder, leave the hidden field empty at first, after the search populate it.
Try this:
function popup(lid)
{
var linkid=lid.id.toString();
var lengthid=linkid.length-25;
var idh=linkid.substring(0,parseInt(lengthid));
var hid=idh+"hiddenfield1";
var gv = document.getElementById("<%=GridViewComplaints.ClientID %>");
var gvRowCount = gv.rows.length;
var rwIndex = 1;
var username=gv.rows[rwIndex].cells[1].childNodes[1].innerHTML;
var prdid=gv.rows[rwIndex].cells[3].childNodes[1].innerHTML;
var msg=document.getElementById(hid.toString()).value;
alert(msg);
document.getElementById('<%= Labelcmpnme.ClientID %>').innerHTML=username;
document.getElementById('<%= Labelprdid.ClientID %>').innerHTML=prdid;
document.getElementById('<%= TextBoxviewmessage.ClientID %>').value=msg;
return false;
}
<ItemTemplate>
<asp:LinkButton ID="LabelComplaintdisplayitem" runat ="server" Text='<%#Eval("ComplaintDisp").ToString().Length>5?Eval("ComplaintDisp").ToString().Substring(0,5)+"....":Eval("ComplaintDisp") %>' CommandName ="viewmessage" CommandArgument ='<%#Eval("username")+";"+Eval("productId")+";"+Eval("ComplaintDisp") %>' class='basic' OnClientClick =" return popup(this)"></asp:LinkButton>
<asp:HiddenField ID="hiddenfield1" runat ="server" Value='<%#Eval("ComplaintDisp")%>'/>
</ItemTemplate>
If the place holder visibility is set to false, it will never be rendered , and the hidden field value will be only stored in the ViewState of the page.
just one question, why are you setting the visibility of the place holder to be false , if its containing a hidden field?
Anyway one possible way to get over this issue, is adding a TextBox or Label object , and set the display CSS style of it to "none" , then in your code copy whatever you are putting in the hidden field into the textbox/lable text property, this way you can easily read the value using javascript , since the textbox/label will be rendered but not visible to others, though this might not be that safe thing to do.
Instead of making ".visible=false", change the style to "display: none;". That will render your control but make it invisible.
Visible doesn't actually make it visible, you can leave it default. Just runat="server" and use its .Value.

How do you set the "Visible" property of a ASP.NET control from a Javascript function?

Bascially I want to know the best way to hide/show an ASP.NET control from a Javascript function. I figured I would just access the control in Javascript using:
var theControl = document.getElementById("txtEditBox");
Then just set the control's Visible property to true/false. It doesn't seem to be working, I can't seem to figure out how to set "Visible" to true/false. How can I do that? Also, is that the best way to hide/show a ASP.NET control from a Javascript function?
Thanks,
Jeff
The "Visible" property of an ASP.NET control determines whether or not it will be rendered on the client (i.e. sent to the client). If it is false when the page is rendered, it will never arrive at the client.
So, you cannot, technically, set that property of the control.
That said, if the control is rendered on the client because the Visible property is true when the page is rendered, you can then hide it using javascript like this:
var theControl = document.getElementById("txtEditBox");
theControl.style.display = "none";
// to show it again:
theControl.style.display = "";
That assumes that the control's id attribute really is "txtEditBox" on the client and that it is already visible.
Also, is that the best way to hide/show a ASP.NET control from a Javascript function?
There is not necessarily a "best" way, although one better approach is to use CSS class definitions:
.invisible { display: none; }
When you want to hide something, dynamically apply that class to the element; when you want to show it again, remove it. Note, I believe this will only work for elements whose display value starts off as block.
instead of using visible, set its css to display:none
//css:
.invisible { display:none; }
//C#
txtEditBox.CssClass = 'invisible';
txtEditBox.CssClass = ''; // visible again
//javascript
document.getElementById('txtEditBox').className = 'invisible'
document.getElementById('txtEditBox').className = ''
Set the style to "display: none".
var theControl = document.getElementById("<%= txtEditBox.ClientID %>");
theControl.style.display = "none";
You can't hide/ show the ASP.NET version of the control as that only exists in a server context. To use JavaScript you need to play with the controls style/ visibility state.
The only kind-of way to do it would be to wrap the control in an UpdatePanel and have something like this:
<asp:UpdatePanel ID="panel" runat="server">
<ContentTemplate>
<asp:TextBox ID="myTextBox" runat="server" />
</ContentTemplate>
<Triggers>
<asp:AsynchronousPostbackTrigger ControlID="button" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="button" runat="server" OnClick="toggle" Text="Click!" />
Then you need this in your code behind:
protected void toggle(object sender, EventArgs e){
myTextBox.Visibility = !myTextBox.Visibility;
}
Now when you click the button an async postback occurs and it will refresh the UpdatePanel.
Note: This is not a good solution, as it'll be a very heavy AJAX request, because you need to submit the ViewState.
Also, it may not be 100% right, I did that from memory.
This should hide the control:
theControl.style.display = 'none';
You can use the display property for this. But as Jason noted, this is a DHTML DOM (client-side) property that is completely independent from the ASP.NET (server-side) Visible property which controls rendering.
theControl.style.display = "none";
Display Property
You want to set the display style property to 'none' (to hide) or null to show.
var theControl = document.getElementById("txtEditBox");
theControl.style.display = 'none';
theControl.style.display = null;
Doing it the jQuery way:
$('#txtEditBox').hide();
$('#txtEditBox').show();
Or if you don't want to use css:
<asp:TextBox ID="txtBox" runat="server" style="display:none;">
I think the best solution is to put your ASP control inside a div and set the property display to the div element.
<div id="divTest">
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
</div>
<script type="text/javascript">
SIN JQuery
document.getElementById('divTest').style.display = "none";
CON JQuery
$('#divTest').hide();
</script>

Resources