Conditional Anchors - c#

I have a website in which I need to have conditional navigation. As such:
Clicked item in Menu
1: if frontpage, go to #id
(example <a href="#events">)
2: if subpage, go to front- or other subpage
(example <a href="../events/>)
The website is a .net website and the navigation is located on the masterpage.
I have thought of different ways to solve this, either with .Net & C#, JS or JQuery.
In .Net I thought I could assign asp controls and simply serve different links in different subpages and then have some sort of loop or replacement with the codebehind.
If anyone has any idea how to figure out this, please write. Thanks in advance!
Code examples:
<li>
Coaching & Consulting
</li>

Why dont dont you create a user control with your menu?
You can check it out here:
http://msdn.microsoft.com/en-us/library/vstudio/fb3w5b53(v=vs.100).aspx
and pass some parameter to the user control and handle the link changing in there.
You can have that menu stored somewhere else, like in a xml file somewhere and render it to the desired html.

I followed Vfleitao's advice and tried User Controls. Just so others can see how I solved it here are some code examples:
The header user control:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="header.ascx.cs" Inherits="menu" %>
<ul class="show-for-large-up">
<li>About us</li>
<li>Coaching</li>
<li>Consulting</li>
<li>Events</li>
<li>Contact</li>
</ul>
Codebehind:
private string aboutUsLink;
private string coachingLink;
private string consultingLink;
private string eventsLink;
private string contactLink;
public string AboutUsLink
{
get { return aboutUsLink; }
set { aboutUsLink = value; }
}
public string CoachingLink
{
get { return coachingLink; }
set { coachingLink = value; }
}
public string ConsultingLink
{
get { return consultingLink; }
set { consultingLink = value; }
}
public string EventsLink
{
get { return eventsLink; }
set { eventsLink = value; }
}
public string ContactLink
{
get { return contactLink; }
set { contactLink = value; }
}
Use in page:
<%# Register TagPrefix="My" TagName="header" Src="~/header.ascx" %> <%-- Maybe this could be moved to the master page? --%>
<My:header runat="server" ID="MyHeader" AboutUsLink="#OmOs" CoachingLink="#Coaching" ConsultingLink="#Consulting" EventsLink="#Events" ContactLink="#Contact" />
Or
<My:header runat="server" ID="MyHeader" AboutUsLink="../about/" CoachingLink="../coaching/" ConsultingLink="../consulting/" EventsLink="../events/" ContactLink="../contact/" />
Sources for help:
http://asp.net-tutorials.com/user-controls/creating/

Related

C# - Sending value to HREF in html

I have written a project in C# in which I load a HTML webpage if an event occurs during teh course of the project usage.
My issue is that inside my html page, I have a href node inside a tag as such:
<a href="http://pseudo01.hddn.com/vod/demo.flowplayervod/flowplayer-700.flv"
style="display:block;width:inherit;height:inherit;background-color: black;overflow:hidden"
id="player">
</a>
I would like to change the href value programatically by sending a C# variable (called myHrefFile) depending on what the user did.
How can this be done?
you can do something like this
<a href="<%= someMethodThatGetHrefValue() %>"
style="display:block; width:inherit;height:inherit; background-color:black;
overflow:hidden"
id="player">click</a>
call the method that decide what should be href for link .
and put all the logic of deciding href in that method like this
public string someMethodThatGetHrefValue()
{
if(someval == true)
return "http://www.google.com";
else
return "http://www.yahoo.com";
}
Something like this perhaps? This is an Asp.net solution.
<asp:LinkButton ID="LinkBut" runat="server" onclick="LinkBut_Click">Click here</asp:LinkButton></p>
protected void LinkBut_Click(object sender, eventArgs e)
{
string myHrefFile = "";
if(Value.equals(true))
{
myHrefFile = "page1.aspx";
}
else
{
myHrefFile = "page2.aspx";
}
Response.Redirect(myHrefFile );
}

ASP.net get content page to change master page control

Master page:
<form runat="server">
<Scirra:MainMenu runat="server" ID="MainMenu" TopTabSelected="home" SubTabSelected="link2" />
<asp:ContentPlaceHolder id="MainContent" runat="server">
snip
Content page:
Master.MainMenu.TopTabSelected = "forum";
I know I'm probably doing this wrong, but is this possible? I want to change a parameter of that control. It says 'inaccessible due to protection level'.
You should provide a public property f.e MenuTabSelected in your MasterPage that Gets/Sets this property of your Menu.
public string MenuTabSelected {
get { return MainMenu.TopTabSelected; }
set { MainMenu.TopTabSelected = value; }
}
Then you can access it in this way:
((YourMasterPage)Master).MenuTabSelected = "forum";
where YourMasterPage is the type of your MasterPage.
The compiler error is thrown because you want to access a private or protected control from outside of your MasterPage-Class. This would only be allowed if it would be public, what is not recommended. You have more control if you do it the way i suggested :)
find menu items in content page and change its value
protected void Page_Load(object sender, EventArgs e)
{
Menu mainMenu = (Menu)Page.Master.FindControl("NavigationMenu");
MenuItem menuMaterials = mainMenu.FindItem("Materials");
if (menuMaterials.Value == "Materials")
{
menuMaterials.Value = "NO materials";
menuMaterials.Text = "No materials";
}
}

Simple user control for conditionally rendering nested HTML

What I would like to do, is be able to pass two attributes to a user control, a ListName and a Permission, like so:
<uc:check id="uc" List="Shared Documents" Permission="OpenItems" runat="server">
<!-- have some HTML content here that is rendered if the permission is true -->
</uc:check>
Then in the actual check user control, have something similar to:
<%# Control language="C#" ClassName="check" %>
<%
// determine permission magic placeholder
if (DoesUserHavePermissions(perm))
{
// render nested HTML content
}
else
{
// abort rendering as to not show nested HTML content
}
%>
I have read the page on creating a templated control on MSDN, and while that would work - it really seems to be a bit overkill for what I am trying to do. Is there a control that already renders content based on a boolean expression or a simpler template example?
http://msdn.microsoft.com/en-us/library/36574bf6.aspx
Update:
The following code can be used in the ascx to model a very simple version of this:
<%# Control Language="C#" ClassName="PermissionCheck" %>
<%# Import Namespace="System.ComponentModel" %>
<script runat="server">
void Page_Init()
{
if (Allowed != null)
{
Panel container = new Panel();
Allowed.InstantiateIn(container);
PermissionBasedMessage.Controls.Add(container);
}
}
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate Allowed { get; set; }
</script>
<asp:Placeholder runat="server" ID="PermissionBasedMessage" />
Note: I oversimplified the check in the Page_Init method for this sample code. Additional logic checks can be added as needed.
And reference it in the calling HTML page:
<%# Register src="PermissionCheck.ascx" tagname="PermissionCheck" tagprefix="uc1" %>
<uc1:PermissionCheck ID="PermissionCheck1" runat="server">
<Allowed>Allowed Access</Allowed>
</uc1:PermissionCheck>
You could create a custom control instead of a user control: derive from the asp.net panel, add your two properties, then only render the control if the user has the required permission. E.g. something like this:
The control (put this in App_Code for example):
namespace MyControls
{
public class MyPanel : Panel
{
public string Permission { get; set; }
public string List { get; set; }
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
if (UserHasPermission()) base.Render(writer);
}
}
}
Using the control:
<%# Page ... %>
<%# Register Namespace="MyControls" TagPrefix="mc" %>
<html>
...
<mc:MyPanel runat="server" List="Shared Documents" Permission="OpenItems">
put content and/or other controls here
</mc:MyPanel>
...
Why don't you extend the LiteralControl, add properties for your settings, then render html to the .Value of the LieralControl? Seems pretty simple and a lot less of a headache than using Templated controls
The other answers are good for the generic form of your question, but for checking permissions SPSecurityTrimmedControl might do what you need.
Wrap your content with a place holder control and set the control's visibility to true or false (controls that have .Visible = false won't render any html)
<asp:PlaceHolder id="phWrapper" runat="server">
...
</asp:PlaceHolder>
Then in your code-behind set phWrapper.Visible = DoesUserHavePermissions(perm);
Hope that helps!

How to select current menu in master pages?

In my web app (asp.net C#) I have menus as "All", "Education", "Fun", "Comedy". I want when I select All then it should be displayed as current menu, for which I have a CSS class current.
In case of WebUserControls I can do it easily by passing parameter of current page to select as below:
mywebpage.aspx
<uc:header ID="header1" runat="server" selectedMenu="comedy" />
header.ascx (code (c#))
public string selectedMenu
{
get { return strSelected; }
set { strSelected = value; }
}
header.ascx (html)
<ul>
<li><a href="/all/" title="All Videos" <%if (strSelected == "all"){%>class="current"<%} %>><span>All</span></a></li>
<li><a href="/fun/" title="Fun Videos" <%if (strSelected == "fun"){%>class="current"<%} %>><span>Fun</span></a></li>
<li><a href="/comedy/" title="Comedy Videos" <%if (strSelected == "comedy"){%>class="current"<%} %>><span>Comedy</span></a></li>
</ul>
When I'll pass comedy from my webpage to usercontrol then it will select comedy menu. I want to implement the same kind of functionality in case of master pages, could anyone tell me how to achieve this type of facility for master pages.
One way what I feel is to pass a query string parameter http://example.com/all/?select=all, I'll check on master page_load function if select parameter is "all" or fun or comedy then select corresponding menu. But this is not good, because I don't want to add an extra query string parameter to my URLs.
Please tell me how to solve this issue.
Thanks
You can access master page properties from your content page after casting the master to the correct type:
public class MyMasterPage : MasterPage
{
public string MyMenuProperty { get; set; }
protected void Page_PreRender(object sender, EventArgs e)
{
if (MyMenuProperty == "comedy")
{
/* do your menu stuff */
}
}
}
public class MyContentPage : Page
{
protected void Page_Load(object sender, EventArgs e)
{
var myMaster = Page.Master as MyMasterPage;
if (myMaster != null)
{
myMaster.MyMenuProperty = "comedy";
}
}
One way i have done simular in the past is add this to the page derivatives of any content pages:
<%# MasterType VirtualPath="~/YourMaster.master" %>
Then in the master i exposed this:
private PageTypes currentPageType;
public PageTypes CurrentPageType
{
get { return currentPageType; }
set { currentPageType = value; }
}
On this job this was used so the master knew what type of page it was on and therefore changed a few things, colours, controls etc. So from a contents pageload i did
Master.CurrentPageType = PageTypes.System;
One thing to note however, VS tends to moan about the MasterType derivative until you do a rebuild all.
I'm thinking that maybe a completely different approach might be easier to implement and maintain.
How about you just parse the URL in your header.ascx?
For example:
<li><a href="/all/" title="All Videos" runat="server" class='<%= Request.Url.ToString().Contains("/all/") ? "current" : "" %>' ><span>All</span></a></li>
That way, you won't have to worry about setting properties, accessing/casting master pages etc...
Hai prashant,
I had the same issue a month back and i posted in stack overflow check this one it may help you Find a UnorderedList <UL> control inside a master page from a content page in asp.net

Bind tag vs codebehind set, best practices

I would like to know what is the best practice between using bind tag and setting direct property to a control in asp.net.
aspx.cs
public string Description {get; set;}
aspx
<asp:Literal ID="txtDescription" runat="server" Text='<%# Description %>' />
aspx.cs
public string Description
{
get { return txtDescription.Text ; }
set { txtDescription.Text = value; }
}
aspx
<asp:Literal ID="txtDescription" runat="server" />
The first being best to separate design from code giving the liberty of changing even ID without breaking code. But it seems we can get very long bind tag sometime like this really short example:
Text='<%# ((fn_SearchReminders)Container.DataItem).dtDateActivation.Value.ToString("yyyy-MM-dd - hh:mm") %>'
The only time it's worth using the binding expressions is when... databinding. For dealing with static controls like your textbox the best way to access it is the way you did in the second case.
This is even the case for dealing with the Model View Presenter implementation where generally your aspx page will inherent from iSomeView and you will access properties similar to
string iSomeView.Description
{
get { return txtDescription.Text ; }
set { txtDescription.Text = value; }
}
Using a method similar to this also allows you to construct complex objects easily:
Person iSomeView.Person
{
get { return new Person { Name = txtName.Text, Phone = txtPhone.Text }; }
set { txtName = value.Name; txtPhone.Text = value.Phone; }
}
If you are using controls like GridView or Repeater and the likes you can simply use
' />
and optionally specify the format string like
' />
where "d" stands for short date string.
In case of other controls which are directly contained in the page you can consider using a private method which will set their properties whenever you feel appropriate.
Like
private void SetFormFields(Employee emp){
lblName.Text = emp.Name;
txtDateOfBirth.Text = emp.BirthDate.ToShortDateString();
}
and call it in the page load event or from some other place.

Categories

Resources