How to select current menu in master pages? - c#

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

Related

Accessing masterpage code behind code from a child pages .ASPX page

I'm looking to execute code in my code behind on my Masterpage, and use it on the .aspx page of child pages like Default.aspx, without having to call it through the Default.aspx.cs page.
This is my attempt by accessing it like so <% MasterPage.getPlanCost() %>, however, this does not work. As there's "no definition" for getPlanCost()
Master Page code behind:
public string getPlanCost()
{
var country = getCountry();
string gbp = "£5.99";
string euro = "€6.99";
string usd = "$8.99";
var currencyCost = usd;
if (country == "United Kingdom") // gbp
{
currencyCost = gbp;
}
else if (country == "United States" || country == "Canada" || country == "Australia" || country == "New Zealand") // usd
{
currencyCost = usd;
}
else // euro
{
currencyCost = euro;
}
return currencyCost;
}
Default.aspx page:
<p class="text-center under-title text-muted"><%=MasterPage.getPlanCost() %> Cancel Anytime.</p>
What is the quickest / most efficient way of achieving this? Furthermore, I have tried to use alternate methods seen on StackOverflow, using get and set however I was unable to get this working. Fairly new to C# so I apologise.
Although you have found a workaround, it is possible to access master page methods from child web forms, useful in cases where want your child page to affect the master page in some way. You can do this through the Page.Master property, but you will first have to register the type or cast it.
Method 1: Registering Master Type
Web Form:
<%# Page Language="C#" MasterPageFile="~/Example.Master" ... %>
<%# MasterType VirtualPath="~/Example.Master" %>
Code Behind:
Page.Master.getPlanCost();
Method 2: Casting Master Property
Code Behind:
((Example)Page.Master).getPlanCost();
To anybody wondering, I created a class called Utilities.cs
Then called it directly from here from my Default.aspx page instead.
<%=Utilities.getPlanCost()%>
I'd also like to thank #Joel Coehoorn for his comments which got me halfway there.

Conditional Anchors

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/

How do I get access to master page properties via user control markup?

I have been searching the internet and most I find resolves the issue of accessing the master page properties from the user control's code behind. But I am unable to find a solution where the user control can have access to the master page's properties within the markup.
Background:
The master page dynamically adds user control onto the page.
The master page has two properties which the user control needs to access via markup.
Here is some code to represent my problem:
Master page's code behind properties:
public IModule Module
{
get
{
return MyContext.Current.Module;
}
}
public IDictionary<string, object> Arguments
{
get
{
return MyContext.Current.Arguments;
}
}
Master page dynamically adds to control in code behind (it HAS to be dynamically added in master page's code behind):
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!(Page is VehicleForm) && !(Page is VsrManageForm) && !(Page is VpbManageForm))
{
MenuTab view = (MenuTab)this.LoadView(plhMenu, "~/Controls/MenuTab.ascx", "", MyContext.Current.Module);
}
}
User control's markup:
<web:FlowLink class="tools__lnk" arguments="<%# Arguments %>" id="flowLink1" runat="server" contextmodule='<%# Module %>' flowcall="FavouritesView" title="" rel="nofollow" ClientIDMode="Omitted">Shortlist</web:FlowLink>
<web:FlowLink class="tools__lnk" arguments="<%# Arguments %>" id="flowLink2" runat="server" contextmodule='<%# Module %>' flowcall="CompareView" title="" rel="nofollow" ClientIDMode="Omitted">Compare</web:FlowLink>
<web:FlowLink class="tools__lnk" arguments="<%# Arguments %>" id="flowLink5" runat="server" contextmodule='<%# Module %>' flowcall="UserView" title="" rel="nofollow" ClientIDMode="Omitted">Account</web:FlowLink>
Error:
Compiler Error Message: CS0103: The name 'Arguments' does not exist in the current context
Question:
How do I access <%# Arguments %> and <%# Module %> master page properties from the user control?
It might be possbile (have not tested it though) to do something like this:
arguments="<%# ((MasterPageType)this.Page.Master).Arguments %>"
Although it does not look right. You might want to redesign the way you control gets the data. Or atthe very least do the same somewhere in code behind and verify whether a current masterpage is of an expected type.
Update. The final solution that OP used incorporated ideas above, and resulted in having properties like below declared in the control:
public IDictionary<string, object> Arguments
{
get
{
MasterPageType master = this.Page.Master as MasterPageType;
if (master != null)
{
return master.Arguments;
}
else
{
return null;
}
}
}

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";
}
}

Setting title of a page

I have an ASP.NET application that uses a master page configuration. What I'd like to do is two things.
How can I programmically set the title in the child page (as in the text in the <title></title> tags? And,
If the child page does not set the title, I'd like the master page to automatically detect this and set a default title.
Any help would be appreciated.
you can have your pages inherit from a custom page
public abstract class CustomPage : Page
{
public virtual string PageTitle {get{return String.Empty;}}
}
Then, in your MasterPage's Page_Load, do ( can't remember if MasterPage.Title exists or if you'll have to do Page.Title, which will work since both objects are Page objects):
if(Page is CustomPage) {
this.Page.Title = ((CustomPage)Page).PageTitle;
} else {
this.Page.Title = "Default Title";
}
Then, when you create a Page, for instance a CustomerManager page:
public partial class CustomerManager : CustomPage
{
public override string PageTitle { get{return "Customer Manager"; }}
}
This way, your MasterPage isn't 100% tied to using CustomPage (creating normal Pages won't throw an error). And, if you use CustomPage objects, you're all set!
What I do is basically the same as Jim Schubert's. I do make one small change though, in the MasterPage's PageLoad, i would do a conditional check, something like the following:
if(Page is CustomPage) {
var cp = (CustomPage)Page;
this.Title = (String.IsNullOrEmpty(cp.PageTitle)) ?
"Master's Default Title" :
cp.PageTitle;
}
This then addresses point 2 of you question, so that your custom pages need not specify a title, but can just return String.Empty.
(Forgive if the syntax isn't exactly right, VB is my native language.)
For your first question,This is the one you are looking for http://www.devasp.net/net/articles/display/852.html and
For your second question, http://delphi.about.com/cs/adptips2004/a/bltip0304_2.htm
In the Master page markup, do this:
<head runat="server" id="hd">
<title></title>
</head>
Then, in code behind (assuming AutoEventWireup="false"):
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (String.IsNullOrEmpty(this.mhd.Title))
this.hd.Title = "Master Title";
}
Then in your page you can either set the title declaratively:
<%# Page Title="Page Title" . . . %>
or programmatically:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.Title = "Page Title";
}
for your 1st question shouldnt:
Protected void Page_Load(object sender, EventArgs e)
{
Page.Title = "Title";
}
for each child page ,Do the trick?
you can add a contenttemplate at the header of the masterpage then add a contentplaceholder at the aspx pages inheriting from the masterpage, then in the pageload of the aspx you can set the title :
page.title = "my title"
to answer the second part, you can simply put the default title in the tag at the master page, so that if you did not set it programmatically then it will stay the same.

Categories

Resources