Changing user control css class in code behind - c#

So I have a user control that displays links and I want to change the color of the link that is currently active.
This is the code inside my ListView of my usercontrol ascx file.
<asp:ListView ID="sidebarListView" runat="server" DataKeyNames="Id" DataSourceID="SqlDataSourceSidebar" OnItemCommand="sidebarListView_ItemCommand">
<ItemTemplate>
<div id="sidebarItemID" class="sidebarItem" runat="server">
<div>
<asp:LinkButton ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' CommandName="Select" CommandArgument='<%# Eval("Id") %>' />
</div>
</div>
</ItemTemplate>
....
I need to change the sidebarItemID class when the linkbutton is clicked.
My default.aspx code behind looks like this:
private void SideBar1_ItemCommand ( object sender , EventArgs e ) {
Int32 facId = Sidebar1.FacultyId;
SqlDataSource1.SelectCommand = "SELECT [Id], [Name], [Faculty_Id], [User_Id], [Author], [Picture], [Location] FROM [Books] WHERE [Faculty_Id]=" + facId + " ORDER BY [DateAdded] DESC";
HtmlGenericControl htmlDivControl = (HtmlGenericControl) FindControlRecursive( Sidebar1 , "sidebarItemID" );
htmlDivControl.Attributes.Add("class", "sidebarItemActive");
string newClass = htmlDivControl.Attributes["class"];
//Response.Write( String.Format( "<script>alert('{0}');</script>" , newClass ) );
}
This correctly changes the sqlDataSource based on the ID of the link clicked in the user control. However the class doesn't change.
If I uncomment the Response.Write(...) section it correctly gives an alert that says "sidebarItemActive" so it correctly finds the control from my page and assigns its class attribute as "sidebarItemActive" but nothing changes on the page if I view the page source in the browser it says the class is still "sidebarItem".
What is going on here that the change does not come into effect?

The actual <div>s on your page are generated during the Render state of the ASP.NET Page Life Cycle. This happens after the Control event handling stage, thus any changes you make to the HTML during your handler function are effectively undone during Render, as the control's HTML is regenerated from the template. To have the control change its internal HTML in this case, you may put your update code in an overridden Render function for your control. The MSDN has an example of how to write the render function.

So I solved the problem by defining the ListViews ItemDataBound event handler and assigning the css class in there. The problem previously was, that since my controls were inside updatePanels the ItemDataBound event was not firing. I had to manually call "DataBind()" inside the click method.
Inside my default.aspx
// Exposed click event, updates RecentBooks control sqlDataSource.
private void SidebarItems1_Clicked ( object sender , EventArgs e ) {
RecentBooks1.updateDataSource( SidebarItems1.FacultyId.ToString() );
SidebarItems1.DataBind();
}
Inside my user control.ascx
protected void sidebarListView_ItemDataBound ( object sender , ListViewItemEventArgs e ) {
LinkButton button = e.Item.FindControl( "NameLabel" ) as LinkButton;
if (FacultyName != null && button != null) {
if ( button.Text == FacultyName ) {
button.CssClass = "sidebarItemActive";
}
}

Related

Asp .net Linkbutton child controls dissapears on postback

I have an asp .net hyperlink control declared like this:
<li runat="server" id="liveChatCtrl" Visible="false"><asp:LinkButton runat="server" ID="hlnkLiveChat" CausesValidation="false" OnClick="hlnkLiveChat_Click">Live Chat Support <i class="icon icon_next_03 fr"></i><i runat="server" id="iconChat" class="icon_chat_online"></i></asp:LinkButton></li>
My problem is that the contents of the linkbutton disappears on postback. Any ideas why this is happening?
On load I execute the following code on the linkbutton or it's children:
string absoluteURL = UtilManager.Settings.Item(Utils.BrandID, "URL:absoluteURL");
string chatLink = "StartChat.aspx";
if (HttpContext.Current.User.Identity.IsAuthenticated)
chatLink = "LiveChat.aspx";//~/
//else
// chatLink = "SalesChat.aspx";
string link = absoluteURL + chatLink;
hlnkLiveChat.Attributes["onclick"] = string.Format("javascript:window.open( '{0}', 'chat', 'status=no,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes,height=505,width=420,left=30,top=30');", link);//"openPopup('" + link + "','chat'); return false;";
liveChatCtrl.Visible = true;
A guess...
I believe you may have the code in your Page_Load (or Init) inside an if(!IsPostBack)
If this is the case, move it outside of this if statement as you need it to run as your default visible for your liveChatCtrl is false
Either that or re-code a little so that your default visible is true and you run a check on postback to hide it if needed.

ASP.Net WebForms LinkButton click, open new tab, passing id through hidden html input variable

I have an aspx webforms page with a repeater built through a user control. Each repeater item has a link button. What I want to happen is that when the LinkButton (in the repeater on page A's user control) is clicked, the url is opened in a new tab, and a hidden id next to that LinkButton is passed (according web development best practices for security if possible) to the aspx page (page B) in the new tab. Both pages A and page B are in the same application.The intent of what I described above is so that the user can easily return to their search results after returning from the URL opened by clicking on the LinkButton.I am open to ideas on how to do this that are closer to standard best-practice methods.
So far, I have tried:
1) cross-page posting – this worked for passing the id, but not for opening in a new tab.
2) Setting the PostBackUrl to page B's url, setting the Page.Form.Target="_blank" with OnClientClick calling javascript to set the hidden id from the user control to the value of an html hidden input on page B and also.
3) I also tried using window.open("page B url", "_newtab") in OnClientClick.
a) So far, the only method that worked correctly was the 2nd one from the 3 different methods above. However, after page B is loaded in the new tab, I don't know how to reset page A's Page.Form.Target back to what it was previously before setting it to "_blank"
b) The methods that I have tried, to no avail, to reset the Page.Form.Target have been:
1) Resetting the target in page A's Page_Load where IsPostBack == true --> that caused Page B to load with the same content as Page A.
2) Resetting the target in page A's user control's Page_Load --> same result as method 1
3) Resetting the target in page A’s user control’s LinkButton’s OnUnLoad in page A's user control --> same result as method 1
4) Resetting the target in javascript through the LinkButton’s OnClientClick --> didn’t work
5) Resetting the target in page B's Page_Load using a public variable from page A containing a reference to page A's form (similar to what can be done through cross-page posting) --> didn’t work.
What I am thinking about trying next is:
1) Wrapping another user control on page A to display page B's content, in an asp Panel (Panel B)
2) Put page B’s content into the new user control page
3) Wrapping the search results content on page A in an asp Panel (Panel A).
4) When the LinkButton in the repeater on the new user control is clicked, the search results content in Panel A will be hidden, and Panel B will be shown.
5) When the user wants to return to the search results, they will click on a ‘Return to Search’ LinkButton in Panel B’s content, and then Panel B will be hidden, then content of Panel B will be cleared, and Panel A will be shown again.
I'm not yet sure if that will work though. It doesn't seem like this should be that difficult. It is a straight-forward concept, and I would think is a fairly common situation in web development.
I feel like Wiley Coyote trying to catch the Road Runner because I come up with elaborate intelligent, thought-out plans that all completely fail. I am now holding up a little sign that says, "Help!
I had the same issue resolve by the following code you just try this in ur HTML page for a button in GRIDVIEW:
<asp:LinkButton ID="LinkButton1" runat="server" Text="View" CommandArgument='<%# Bind("ref") %>'
OnClick="LinkButton1_Click" OnClientClick="document.forms[0].target ='_blank';">View</asp:LinkButton>***
I actually got this figured out.
I figured it out through a combination of the marked-answer on this post, How to Open new tab when we click on LinkButton, and the marked-answer on this post, Is it possible add click event to hyperlink?.
My Repeater ItemTemplate in the user control's repeater looks similar to this:
<asp:HiddenField ID="hfId" runat="server"
Value='<%# Eval("Id") %>'/>
<asp:HyperLink ID="myLink" runat="server"
Text='<%# Eval("Name") %>'
NavigateUrl="/myUrl.aspx"
Target="_blank" />
<asp:Button ID="btnSubmit" runat="server"
Text="Submit"
OnClick="BtnClick"
Style="display: none;" />
This is my code in the ItemDataBound of the repeater:
protected void RptrItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var myId = "";
var myNameLink = e.Item.FindControl("myLink") as HyperLink;
if (myNameLink != null)
{
var submitButton = e.Item.FindControl("btnSubmit") as Button;
if (submitButton != null)
{
var submitButtonClientId = submitButton.ClientID;
myNameLink.Attributes.Add("onclick", "onNameClick('" + submitButtonClientId + "')");
}
}
}
}//end RptrItemDataBound
The javascript code:
<script type="text/javascript">
function nameClick(buttonId)
{
document.getElementById(buttonId).click();
}
</script>
And here is the BtnClick C# code:
protected void BtnClick(object sender, EventArgs e)
{
var btnSelect = sender as Button;
if (btnSelect == null)
{
return;
}
var myListItem = (RepeaterItem)btnSelect.DataItemContainer;
if (myListItem != null)
{
var hfId = myListItem.FindControl("hfId") as HiddenField;
if (hfId != null)
{
var intId = int.Parse(hfId.Value);
Session["selectedId"] = intId;
}//end if (hfId != null)
}//end if (myListItem != null)
}//end btnClick

ASP.NET OnClick not firing in Repeater.ItemTemplate that has a custom control

Title is a bit of a mouthful, but I'm a bit stuck on this issue.
I have a search result page with has a custom control that has a Repeater. The ItemTemplate in the repeater is a PlaceHolder so I can construct the Item in a particular format; more specifically, I have a string of 'diseases' that come in the form of Disease1|disease2|disease3 and need to be given links for each disease.
Now for some code:
The following is the SearchResultControl.ascx
<asp:Panel ID="SearchResultPanel" runat="server" ScrollBars="Auto">
<asp:Repeater ID="Repeater1" runat="server"
onitemcreated="Repeater1_ItemCreated"
onitemcommand="Repeater1_ItemCommand">
<ItemTemplate>
<asp:PlaceHolder ID="ItemTemplatePlaceHolder" runat="server">
</asp:PlaceHolder>
</ItemTemplate>
<SeparatorTemplate>
<tr>
<td colspan="6"><hr /></td>
</tr>
</SeparatorTemplate>
</asp:Repeater>
</asp:Panel>
The code behind: SearchResultControl.ascx.cs
protected void Repeater1_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.DataItem != null)
{
PlaceHolder placeHolder = e.Item.FindControl("ItemTemplatePlaceHolder") as PlaceHolder;
Control searchResultItem = Page.LoadControl("SearchResultItem.ascx");
DataRow row = (e.Item.DataItem as DataRowView).Row;
if (row != null)
{
string diseaseState = row["DiseaseStates"] as string;
searchResultItem.GetType().GetProperty("DiseaseStates").SetValue(searchResultItem, diseaseState, null);
placeHolder.Controls.Add(searchResultItem);
}
}
}
(Full disclosure, I got this idea from this question)
The SetValue calls the DiseaseStates property in SearchResultItem which in turn calls the following method to build the links, set the text, and the events:
private void BuildDiseaseStateLabels(string diseaseStates)
{
PlaceHolder placeHolder = FindControl("DiseaseStatePlaceHolder") as PlaceHolder;
string[] diseaseStateSplit = diseaseStates.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
int count = diseaseStateSplit.Length;
foreach (string diseaseState in diseaseStateSplit)
{
LinkButton diseaseStateLink = new LinkButton();
diseaseStateLink.Text = diseaseState;
//diseaseStateLink.Click += new EventHandler(OnDiseaseStateLinkClick);
diseaseStateLink.CommandArgument = "<%# Eval(\"PatientID\")+ \";\" + Eval(\"PatientStatus\")+ \";\" + Eval(\"Age\")+ \";\" + Eval(\"DiseaseStates\")%>";
diseaseStateLink.CommandName = "OnDiseaseStateLinkClick";
//diseaseStateLink.Command += new CommandEventHandler(OnDiseaseStateLinkClick);
placeHolder.Controls.Add(diseaseStateLink);
if (count != 0)
{
Label splitLabel = new Label();
splitLabel.Text = "|";
placeHolder.Controls.Add(splitLabel);
}
}
}
This is the layout for the SearchResultItem
<div id="SearchResultItemDiv" class="MainSearchResultItem">
<asp:PlaceHolder ID="DiseaseStatePlaceHolder" runat="server">
</asp:PlaceHolder>
</div>
Initially I tried setting the Click event, but that doesn't work at all. I then set the CommandArgument and CommandName but that didn't seem to do the trick. I figured the Command event might need to be set, but again, no luck. I should note that when a link is clicked the Repeater1_ItemCreated in SearchResultControl.ascx.cs is called. But since there is no data in e.Item.DataItem is null and I lose the results.
In one of the questions regarding the same issue, it was suggested that the OnItemCommand be added, but even that doesn't get called.
I also read A Stumper of an ASP.NET Question and A Stumper of an ASP.NET Question: SOLVED!, to no avail.
What could I possibly be doing wrong? All of the correct event hookups seem there, I'm checking for IsPostBack and not doing DataBind() again. blaaargharaggh
Help is always greatly appreciate.
I believe you're running into this issue because the LinkButton controls are recreated too late in the page lifecycle. You have to remember that when the page is posted back, the control technically does not exist anymore, so the event handler cannot be fired.
If you can recreate the LinkButton controls somewhere before the Page_Load event is reached, like OnInit for example, everything should work fine.
For simple pages the above usually works very well, but there are circumstances where recreating controls during OnInit requires a lot of overhead, such as storing counters or arrays in ViewState so you can keep track of the controls that need to be recreated after postback. In these situations I would suggest taking a look at the DynamicControlsPlaceHolder by Denis Bauer. This control is capable of persisting dynamic controls without any addtional code required, which is pretty awesome.
Here's a link to the latest version:
http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
The problem might be that you're not doing the DataBind() again.
Because you're building the buttons on the fly, when the page post backs, the buttons haven't been created and are unable to work out which click event it should be firing.
Try getting rid of the IsPostBack check, so each time the page loads, you're re-build the repeater.

ASP, Listview conditional Alert

I'm currently working with a listview in which I want an htmltablecell to possess the onclick property which is driven by the codebehind rather than a javascript.. However I'm guessing that's pretty much a dream getting it to obey the C# code... Anyways this is what I want it to run:
protected void show_anm(object sender, EventArgs e)
{
Label hiddenc = (Label)listview1.FindControl("hidden");
Alert.Show(hiddenc.Text);
}
and here's the Alert class
public static class Alert
{
public static void Show(string message)
{
string cleanMessage = message.Replace("'", "\\'");
string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
Page page = HttpContext.Current.CurrentHandler as Page;
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
}
}
}
The point is creating a listview with a two conditional tablecells, one which appears only when a certain condition is met and the other appears every other time (that's alredy sorted out). Where the one demanding a condition is Clickable, and upon clicking it it'll display an Alertbox with Data from a specific DB cell...
Sorry if my language and the question seemes off, English isn't my native language and I haven't doused myself in Coffe yet.
Any help on the matter would be most appritiated
EDIT1*
<asp:Listview ................
<ItemTemplate>
<tr ......>
<td id=default .....>
<asp:label ........ Text='<%# eval("stuff") %> />
</td>
<td id=conditional onclick=alert()..........>
<asp:label ......... Text='<%# eval("stuff") %> />
</td>
<td id=hidden visible=false ...........>
<asp:label ......... Text='<%#eval("stuff i want in alert") %>' />
.....
<script tyupe="text/javascript">
function alert()
{
var msg = document.getElementById("tried with label id and tablecell id nothing seemingly worked").value;
alert(msg);
}
</script>
I recently made a workaround that shows the data I want to display in the labels tooltip but I'd still prefer the alertbox to work properly as it feels more natural to click something.
Edit2 In case anyone is wondering I used the ItemDataBound event to bind the visibility of cells default and conditional within an if clause to make sure the control exists and the conditions are met.
I am confused as to why you're doing what you're doing. Why do you want the codebehind to handle an onclick event of a htmltablecell when you are pumping out javascript to show an alert anyway?
Why not just handle the whole logic within Javascript?
A postback from a htmltablcell will also require javascript
Set your tablecell to call a javascript function which would obtain the alert text from the hidden value and display that;
function ShowAlert()
{
var message = document.getElementbyId("hidden").value;
alert.show(message);
}

Fetch JS return value in server side page_load event in asp.net

I have an aspx master/content page scenario. The parent page has an IFrame which points to a child.aspx. The child.aspx has a checkbox, On page_load of child.aspx, I want to show/hide the checkbox depending on the following logic:
- if the child.aspx is opened directly, then I have to show the checkbox.
- if the child.aspx is opened in the IFrame, then I have to hide the checkbox.
Basically, I want to check in child.aspx, if it contains a parent window then hide the checkbox control otherwise show it.
I will prefer the show/hide code in codebehind in Page_load event as I have to execute some more logic depending on whether the it is opened from parent window or not.
Till now I did the following:
In child.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
<script language="javascript" type="text/javascript">
function DoesParentExists()
{
var bool = (parent.location == window.location)? false : true;
var HClientID ='<%=hfDoesParentExist.ClientID%>';
document.getElementById(HClientID).Value = bool;
}
</script>
<div>
<h2>Content - In IFrame</h2>
<asp:HiddenField runat="server" id="hfDoesParentExist" />
<asp:CheckBox ID="chkValid" runat="server" />
<asp:ImageButton ID="ImageButton_FillW8Online" ImageUrl="~/images/expand.gif"
OnClick="btnVerify_Click" runat="server" style="height: 11px" />
</div>
</asp:Content>
in client.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DoesParentExists", "DoesParentExists()", true);
if (hfDoesParentExist.Value == "true")
{
chkValid.Visible = false;
}
}
Using RegisterClientScriptBlock, I get error in JS. That the object hfDoesParentExist doesn't exist 'coz the control is not yet created. Right? I tried using RegisterStartupScript but in codebehind I always get null in hidden variable. I don't want to use the on button click or something like it. I need it on page_load event only. How to resolve the issue?
This line:
document.getElementById(HClientID).Value = bool;
Should be: (lower case value)
document.getElementById(HClientID).value = bool;
Also you cannot check the value of a hidden field set by javascript register callback, in the current executing context on the server side.
I would move the logic to the client side to hide or show the checkbox. If the field must indeed be removed from the page you can do that as well with javascript.
function DoesParentExists()
{
var bool = (parent.location == window.location)? false : true;
var cehckboxId ='<%=chkValid.ClientID%>';
if(bool){
document.getElementById(cehckboxId).style.display = 'none';
}
else {
document.getElementById(cehckboxId).style.display = 'block';
}
}
You may want to wrap the checkbox with a div and hide the container also to include the label.
To do it server-side, I would rely on a querystring parameter. Have the parent page load the child page by appending ?inframe=1. Then check for that value in your Page_Load.

Categories