FindControl results in null reference - asp.net

I have anchor tags like this
<div id="menu_container">
<ul id="nav-bar">
<li>Home</li>
<li><a href="Account.aspx" runat="server" id="menu_item_account" >Account</a></li>
<li>Servers</li>
<li>Statistics</li>
<li>Tutorials</li>
<li>Contact us</li>
<div id="login_registration_container">
Sign in / Register
</div>
</ul>
</div>
I want to change the CSS class for menu_item_default this way:
WebControl wc = (WebControl)FindControl("#menu_item_default");
wc.Attributes.Add("class", "value");
error: null reference exception
How can this be done?

You shouldn't use '#' symbol in the FindControl argument:
WebControl wc = (WebControl)FindControl("menu_item_default");

Using a MasterPage and the element is in a ContentPlaceholder:
If so then you must retrieve the ContentPlaceholder first, and from it retrive the element you want.
If your page has the following Content-area for example:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
Then you would do the following (error handling omitted):
var mainCtrl = Master.FindControl("MainContent");
var anchor = (HtmlAnchor) mainCtrl.FindControl("menu_item_default");
anchor.Attributes.Add("class", "value");
Using a MasterPage and the element is in the MasterPage:
use:
var anchor = (HtmlAnchor) Master.FindControl("menu_item_default");

Is there a particular reason you are using a regular anchor tag? Why not use an ASP.Net LinkButton? That will make it much easier to reference in the code.
If the control is on the master page, try
Master.FindControl()

Related

show/hide css menu item depending user role using asp.net

I have the css layout: One column fixed width layout, from maxdesign.com
I have two menu items defined like the following:
<div id="navigation">
<ul>
<li>Data Entry</li>
<li>Reports</li>
</ul>
</div>
Now, let's say that I have two roles: guest and operator, and I want that for example if a user with role guest is logged in, then just the Report item from the menu appear, and in case of a user operator is logged in, then both options appear.
How can I accomplish that?
EDIT:
Based on your responses, I'll go with the server side logic to deal with this:
<div id="navigation">
<ul>
<li><asp:LinkButton ID="lkbDataEntry" runat="server">Data Entry</asp:LinkButton></li>
<li><asp:LinkButton ID="lkbReports" runat="server">Reports</asp:LinkButton></li>
</ul>
</div>
Thanks!
You can put this in the Page_Load..
Dim cs As ClientScriptManager = Page.ClientScript
If Not cs.IsClientScriptBlockRegistered(Me.GetType(), "RoleVariable") Then
Dim js As New String
js = "var _role = " & role & ";"
cs.RegisterStartupScript(Me.GetType(), "RoleVariable", js, True)
End If
And from there, you will have the role in the Javascript realm, where you can manipulate the visibility of the items you want.
So...
<script type="text/javascript">
function hideStuff() {
if (_role === "operator") {
// hide/show your elements here
}
else if (_role === "guest") {
// hide/show your elements here
}
}
</script>
Keep in mind that this approach is all client-side and is therefore easy for another developer to manipulate if they really wanted to. But on the other hand, it's the simplest. Don't use this approach for high-security situations.
You could give your menu elements an ID attribute and then in your codebehind either use RegisterClientSideScriptBlock or use Response.Write to send JavaScript to the client to hide (or show) elements based on some condition.
how about something simple like?
<% if(Page.User.IsInRole("operator") || Page.User.IsInRole("guest")) { %>
<div id="navigation">
<ul>
<% if(Page.User.IsInRole("operator")) { %>
<li>Data Entry</li>
<% } %>
<li>Reports</li>
</ul>
</div>
<% } %>
I don't 100% think you can (or should) be doing logic operations with stylesheets. You may need to have some javascript and then decide based on guest or operator which style to display

<a href or <asp:hyperlink.....tag does not render at runtime

i am trying to display a simple div with hyperlink that represents x
like this:
So, when my run my app i see the div but i dont see the x which is <a href tag
and here is my code:
<div class="success">×status message here...</div>
and when i looked at the source of the page this is what it renders:
<div id="ctl00_ctl00_ContentMain_ContentMain_employee_status" class="success" style="display:block;">status message here...</div>
and then i tried with <asp:hyperlink....
<div class="success" id="divStatus" visible="false" runat="server"><asp:HyperLink id="success" runat="server" CssClass="close" Text="×"></asp:HyperLink></div>
and i still dont see href tag, what is going on here and why i am not able to render the <a href or <asp:hyperlnk tag any clue?
i am writing InnerHtml divSuccess.InnerHtml ="status message here...
if thats the case that erasing its static contents then what is the
alternate?
If divStatus contains controls that you want to keep, then you can append HTML to it by using a Literal control and adding it to the controls collection, like:
var lit = new Literal();
lit.Text = "my text or <strong>html</strong>";
this.divStatus.Controls.Add(lit);
Alternatively, you could use another control inside divStatus and alter its inner HTML:
<div id="divStatus" runat="server">
<a id="lnk1">This is the link that we don't want to be removed.</a>
<asp:Literal runat="server" id="litStatusHtml" />
</div>
here is how i able to solved my question
divStatus.InnerHtml = "<a href='#' class='close'>×</a>" + "status message here...";

#Eval if statement in repeater

I'm trying to check a string value inside a repeater, and if it has value then write a link, but can't seem to get it to work. If there is a value in myUrl then I want to display the link.
<%if( %> <%#Eval("myURL").ToString().Length > 0 %>
<a title="myTitle" target="_blank" href="<%# Eval("myURL") %>">my link</a>
<% } %>
Can anyone please help?
try this code !!!
<%#Eval("myURL").ToString().Length > 0 ?
"<a title='myTitle' target='_blank' href='<%# Eval("myURL") %>'>my link</a>":""%>
I personally hate using conditional logic like that in the page.
There are two options that I think are better. You could have a Hyperlink control in the repeater - and set the visibility depending on if the myURL param is there.
visibility='<% #Eval("myURL").ToString().Length > 0 %>'
OR what you can do is have a method on your code behind that you call back to with the "myURL" param.
E.g.
public string CreateURL(string myURL){
if(!string.IsNullOrEmpty(myURL)){
return "<a ... ";
}
return string.Empty;
}
And call in ASPX
<%# CreateURL(Eval("myURL").ToString()) %>
NB this is untested code but this is the ways I usually do this sort of thing.
I would use the String.Format and include the HTML as part of the string. Admittedly, it's not the neatest piece of code ever written, but in my opinion it's the best option:
For example the below will output an anchor tag if the property Url exists, otherwise it will output a span.
<%# string.Format(Eval("Url") != null ? "{1}" : "<span>{1}</span>", Eval("Url"), Eval("Text")) %>">
Try adding a runat="server" and then add a script block for the (new) server-side visible property:
<a title="myTitle" target="_blank" href="<%# Eval("myURL") %>" runat="server" visible='<%#Eval("myURL").ToString().Length > 0 %>'>my link</a>
this will help
How do I run an if statement in aspx?
http://forums.asp.net/t/1254412.aspx/1
http://forums.asp.net/t/1161705.aspx
You can also call your public function inside code behind file:
<%# MyFunction(Eval("myURL").ToString().Length) %>

change master page <a href link from content page

i have this on my master.page
<ul class="menu">
<li class="first" runat="server" id="Li2">
<a runat="server" id="A1" href="../NewEntry.aspx">Create a New Entry</a>
</li>
</ul>
when i go to content page ("NewEntry.aspx") i want the link name to be changed to "Update Entry"
<ul class="menu">
<li class="first" runat="server" id="Li2">
<a runat="server" id="A1" href="../UpdateEntry.aspx">Update Entry</a>
</li>
</ul>
any feedback?
Make the link an asp:Hyperlink. Then have the master page expose a function or property:
public void SetLink(string href, string text)
{
A1.NavigateURL = href;
A1.Text = text;
}
Call the function from the main page.
You can use a hyperlink control <asp:hyperlink> and set the url as well as the text values.
I would recommend handling this as a HyperLink control as others have mentioned. If for some reason you must handle this as a server-side HTML anchor, you can access it using the following code from your webform code-behind:
HtmlAnchor link = (HtmlAnchor)(this.Master).FindControl("A1");
link.InnerText = "Update Entry";
You can also define a content place holder where you have "Create a New Entry". Leave that as the default inside that place holder, and only in the content page set content for it to Update Entry.

How can I disable the Menu control from styling itself in javascript?

I'm using Visual Studio 2010 and ASP.NET 4.0 to render a Menu control as an HTML list so I can style it using CSS. Here is the code I am using below
<asp:Menu ID="navlist" runat="server" Orientation="Horizontal"
SkipLinkText="" ClientIDMode="Static" DataSourceID="MenuSource"
MaximumDynamicDisplayLevels="0" IncludeStyleBlock="False"
StaticDisplayLevels="2">
</asp:Menu>
This produces the following HTML
<!-- URL shortened -->
<script src="/WebResource.axd?...t=634066906994188146"type="text/javascript"></script>
<div id="navlist">
<ul>
<li>Link 1</li>
<li>Link 2</li>
</ul>
</div>
At first glance this looks like exactly what I wanted. However, if I open up WebResource.axd there is a whole bunch of javascript code related to the menu. Part of this code is applying it's own inline styles to the list. Using FireBug I can view the HTML markup after the javascript has executed and it looks something like this:
<div id="navlist" style="float: left;">
<ul class="level1 static" tabindex="0" style="position: relative; width: auto; float: left;" role="menubar">
<li role="menuitem" class="static" style="position: relative; float: left;">
Link 1
</li><li role="menuitem" class="static" style="position: relative; float: left;">
Link 2</li>
</ul>
</div>
These inline styles ultimately affect the layout of my page. I have no need for any of the scripts in WebResource.axd. How can I prevent this script from being rendered in the final markup of the page?
You can tell the menu to NOT style itself if you want to just use the IncludeStyleBlock Attribute
By default its turned on "true"
<asp:Menu IncludeStyleBlock="False" />
On your css use the !important
I've created a custom menu (derived from System.Web.UI.WebControls.Menu) and replaced the OnPreRender:
public class MyCustomMenu : System.Web.UI.WebControls.Menu
{
protected override void OnPreRender(EventArgs e)
{
// Don't call base OnPreRender
//base.OnPreRender(e);
}
}
That did the trick.
You can't do much to change the out-of-the-box functionality of the Menu control. However, you could either create your own control or use the CSS Control Adapter Toolkit.
I tried to override the asp:menu with a custom class, but still haven't learned how to simply remove all attributes from the ul, li, and a tags so that I could apply my own css code to a clean list.
Imports Microsoft.VisualBasic
Namespace MCO
Public Class MyCustomMenu
Inherits Menu
Protected Overrides Sub OnPreRender(e As EventArgs)
' don't use this:
' MyBase.OnPreRender(e)
' but leaving this blank produces NO rendered menu
End Sub
End Class
End Namespace
I have also tried the jQuery method:
$("#navlist li,#navlist li a,#navlist ul,#navlist div").removeAttr('style');
But because the .net webresource is the last thing to run, I found that jQuery line didn't work. It should, but doesn't. :(
I managed this by removing inline styles and changing some class names via jQuery. Of course you can re-style every element but it just produces a lot of unnecessary css code.
Use this, if you want to remove those inline styles from li, a, ul and divs:
$("#navlist li,#navlist li a,#navlist ul,#navlist div").removeAttr('style');
Second you can change those class names e.g.:
$("#from-this-element").removeClass(.remove-me).addClass('.new-class');
And I think it's the best way to use this script after the page has loaded.

Resources