Title on Master Page on ASP.Net MVC - asp.net

To manage page title on page's,I have a master page where i am taking ContentPlaceHolder.
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /> </title>
and on every page i write
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">Some Title Here
</asp:Content>
Now my client ask me for remove title on all page's and keep it on master page but not remove content place holder code on all page's and master page so that in future if any requirement then we can insert data in to them.
So my problem is without removing them on master page and pages i am not able to put title on master page.So how can i handle this situation?

Thanks Guys.. I got solution
if you want to set part of the title from within the master page. For example, you might want the title of every page to end with a suffix, “ – MySite”.
If you try this (notice the – MySite tacked on):
<%# Master ... %>
<html>
<head runat="server">
<title>
<asp:ContentPlaceHolder ID="titleContent" runat="server" /> - MySite
</title>
</head>
And run the page, you’ll find that the – MySite is not rendered. This appears to be a quirk of the HtmlHead control. This is because the title tag within the HtmlHead control is now itself a control.
The fix is pretty simple. Add your text to a LiteralControl like so.
<%# Master ... %>
<html>
<head runat="server">
<title>
<asp:ContentPlaceHolder ID="titleContent" runat="server" />
<asp:Literalrunat="server" Text=" - MySite" />
</title>
</head>

If you want a good solution to overriding the page title:
Create a class of your own that inherits from the System.Web.Mvc.ViewPage.
Have your view pages inherit from that class:
Write a Page_Load handler in your new class that does something like this:
Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Me.Title = "Company Name | " + Page.Title
End Sub
You also don't need a content place holder to change the title. The <head> tag is already a runat server control. Setting the Page.Title in the page load (or earlier event) work just fine.
You could also put a runat server script tag in your master page to accomplish this task too.

Easiest way:
Move the current ContentPlaceHolder somewhere to your HTML, and wrap it in a <asp:PlaceHolder runat="server" visible="false"/>. When you'll be needing it later on, just move the ContentPlaceHolder back again.

Use the OnPreRender event on the master page to set the title, overriding what has been set on each page.

why not add attribute Visible=false to ContentPlaceHolder of Master Page
I think this is the easiest way to handle your situation.
Happy coding.

Related

First link to internal page works. Subsequent attempt causes Http 404 Error in ASP.net 2.0

I am using ASP.net 2.0 in VS 2008 with Framework 3.5, VB.net codebehind
I plan to build a website that would have a stationary menu on the left made with a TreeView in a fixed position div. A second div on the right would be for content. I have made a small test app to see if the concept works using Master / Content pages.
I want the menu to be hard coded in a single place. The Master page works well for that. The idea is to not have to edit the menu in separate pages as the site grows.
The test app has one Master page and one Contents page. That is how I would like to set up the actual website. The Contents page is the start up page. The Master page has the menu items. Each menu item links to Contents.aspx, but with a unique querystring or /keywords appended. The Contents page codebehind Load event reads the Request.Url.AbsoluteUri. Then, based on the appended querystring or /keywords, pulls the content data and pushes it to an empty Literal control on the Contents.aspx page. In this test app I just push plain text for simplicity.
This works well until I re-click a link. That causes an Http 404 error. I have tried using Response.TrySkipIisCustomErrors = True at the top of the Master and Content Load events and that did not help. I can click one menu link several times and the page will keep reloading. But going back and forth between the links causes the error.
When the error occurs it happens before the Contents.aspx Load event starts.
I would like to be able to fix this in a way that will work on an asp.net host site.
MasterPage.master:
<%# Master Language="VB" CodeFile="MasterPage.master.vb"
Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div style="position:fixed; top:0px; left:0px; width:300px; height:100%;
background-color:#ddd; padding-top:10px; padding-left:10px" >
Home<br />
<a href="Contents.aspx?p=ABCD" >ABCD page</a><br />
<a href="Contents.aspx/?p=WXYZ" >WXYZ page</a><br />
</div>
<div style="position:absolute; top:0px; left:310px; width:40%;
height:100%; background-color:#eee; padding-top:10px; padding-left:10px" >
<asp:ContentPlaceHolder id="MainContent" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Contents.aspx
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Contents.aspx.vb"
Inherits="Contents" MasterPageFile ="~/MasterPage.master" title="Contents"%>
<asp:Content ID="Contents" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:Literal ID="Contents_Main" runat="server">
</asp:Literal>
</asp:Content>
Contents.aspx.vb codebehind:
Partial Class Contents
Inherits System.Web.UI.Page
Public Sub Contents_Load(ByVal sender As Object, ByVal e As EventArgs)
Handles Me.Load
Try
Dim url As System.Uri = Request.Url
Select Case True
Case url.AbsoluteUri.EndsWith("?p=ABCD")
Me.Contents_Main.Text = "content for ABCD"
Case url.AbsoluteUri.EndsWith("?p=WXYZ")
Me.Contents_Main.Text = "content for WXYZ"
Case Else
Me.Contents_Main.Text = "Landing Page"
End Select
Catch ex As Exception
Me.Contents_Main.Text = ex.Message & ex.StackTrace
End Try
End Sub
End Class
I was able to solve this by using the same concept in a single aspx form, rather than Master/Content. The menu is now in that single form and the codebehind pulls the data for the content. I do not know what was causing the Http 404 error, but using the single aspx form resolved it. Also, the URL must include a querystring, in the form of www.example.com?s=values, not www.example.com/keyword1-keyword2. The latter syntax also threw the 404 error.

loading javascript file in ASP.NET for a single page

I'm using ASP.NET with a master page containing a script manager. I want to add a javascript file to only one page, but all pages inherit from the master. What is the proper way to accomplish this?
thanks in advance
Add a script manager proxy to the page you wish to add the javascript to and then add the javascript reference using the script manager proxy
In the Master Page add a content container in the HEAD section, in your page put the Javascript tag inside the instance of that container.
EDIT - for d03boy
On MasterPage:
<head runat="server">
<asp:ContentPlaceHolder ID="HeadContent" runat="server" />
</head>
On ContentPage:
<asp:Content ID="LocalHeadContent" ContentPlaceHolderID="HeadContent" runat="server">
<script type="javascript" \>
</asp:Content>
For any content page that doesn't have something to include in the page header there's no need to even create the Content tag.
Can you just use the ClientScriptManager?
if (!Page.ClientScript.IsClientScriptIncludeRegistered("MyKey"))
{
Page.ClientScript.RegisterClientScriptInclude("MyKey", "~/js/script.js");
}
There are a couple of ways to accomplish what you are looking for.
1- put a content place holder in the section of your master page
<head runat="server">
<asp:ContentPlaceHolder runat="server" ID="JavascriptPlaceHolder">
</asp:ContentPlaceHolder>
</head>
and in the specific page you want to add a javascript file add:
<asp:Content ID="Content2" ContentPlaceHolderID="JavascriptPlaceHolder" Runat="Server">
<script type="text/javascript" src="myfile.js" ></script>
</asp:Content>
2- When you are not using Update Panels, use the ClientScript:
Page.ClientScript.RegisterClientScriptInclude("MyKey", "/myfile.js");
3- When using Update Panel and partial page rendering, use the ScriptManager object to register your javascript: (For a script that should be available for the onload event or at least be available when an update panel refreshes)
string javascript_string = "function myAlert(){ alert('me'); }";
ScriptManager.RegisterStartupScript(this, typeof(string), "MyKey", javascript_string, false);
Use the content place holder where you can, then use either other technique when you can't.
How to embed javascript into a content page?

Proper use of MasterPages

I've been looking into different methods of implementing masterpages.
Use the masterpage only for layout, include common controls on every page
Include controls on the masterpage, use a masterpage abstract base class and override it's properties in the masterpage class. This caused the masterpage events to no longer wire up. I could probably fix this, but it's a long way to go just for a single textbox value.
use good 'ol Page.Master.FindControl()
I've read that findcontrol should be avoided (uses magic "label1" strings, supposedly uses too many resources) and masterpages are only for layout. If masterpages are only for layout, do I copy and paste common controls across 100's of pages?
What's the best practice that deals with displaying and accessing common site controls (like a search)? Considering the alternatives, using findcontrol to get a masterpage control doesn't seem that bad.
MasterPages are classes just like a normal Page object. That means you can expose internal controls through public properties to allow child Pages to access without having to resort to Master.FindControl(). To do this you just need to set the MasterType property in the page (I think it may work even without setting this but with this you get intellisense support and avoid having to do casts).
Here's a basic example (sorry it's in VB - this is copying and pasting from an old project):
Master page (.master):
<%# Master Language="VB" CodeFile="default.master.vb" Inherits="DefaultMaster" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form runat="server">
<ASP:TextBox ID="Search" RunAt="Server"/>
<ASP:ContentPlaceHolder ID="Content" RunAt="Server"/>
</form>
</body>
</html>
Master code-behind (.master.vb):
Partial Class DefaultMaster : Inherits MasterPage
Public ReadOnly Property SearchBox() As TextBox
Get
Return Search
End Get
End Property
End Class
Accessing page (.aspx):
<%# Page Language="VB" MasterPageFile="default.master" CodeFile="page.aspx.vb" Inherits="ExamplePage" %>
<%# MasterType TypeName="DefaultMaster" %>
<ASP:Content ContentPlaceHolderID="Content" RunAt="Server">
<p>This is some content on the page.</p>
</ASP:Content>
Accessing page code-behind (.aspx.vb):
Partial Class ExamplePage : Inherits Page
Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs) Handles MyBase.Load
Master.SearchBox.Text = "This page now has access to the master's search box."
End Sub
End Class
Agreeing that master pages are only for layout, would a sensible approach not to farm out the common controls to usercontrols and include them in the master page this way.

master page generating a second title tag

I have a simple page inside a master page (well, in a master in a master).
In the top master I have the head tag with runat="server", with a number of bits such as scripts, stylesheets, etc. and also a contentplaceholder. There is no title tag here.
In the page that uses this master, the content for the placeholder contains the
<title>pagename</title> bit in it. I really have to set it in there.
Unfortunately when the page is rendered I get my title which is all good, but also get a second blank title tag - I presume dumped in there by .NET.
Is there any way of stopping this second title tag coming out?
From memory, by virtue of putting the runat="server" on the <head> .Net automagically adds a <title> if there isn't one already.
I think (haven't tested it) is if in your masterpage you do
<head runat="server">
Blah
<title runat="server" visible="false"></title>
</head>
setting the Title tag explicitly in the Head of the masterpage and setting visibility to false works. I think.
You don't have to manually insert <title> to the head.
Just set Page.Title = "title" by code, or <%# Page Title="My Title" .. %> by markup.
ASP.NET will figure out the rest, and put the right title.
I think using:
If you want to set title at page level
<%# Master ... %>
<html>
<head runat="server">
<title>
<asp:ContentPlaceHolder ID="titleContent" runat="server" />
</title>
</head>
Or,
If you want to set dynamic title at Master Page level.
<%# Master ... %>
<html>
<head runat="server">
<title>
<asp:Literal ID="litPageTitle" runat="server"></asp:Literal>
</title>
</head>
is better way to make sure that empty second title tag is not generated.

ASP.NET MVC - View with master page, how to set title?

What is prefered way of setting html title (in head) for view when using master pages?
One way is by using Page.Title in .aspx file, but that requires in master page which can mess with HTML code. So, lets assume no server side controls, only pure html. Any better ideas?
UPDATE: I would like to set title in view NOT in the controller or model.
In our master pages, we created both an "init" ContentPlaceHolder, and a "title" ContentPlaceHolder. If someone wants to programatically set Page.Title, they can set it in CSharp in the init placeholder, or they can override the "title" placeholder using tags.
Master Page
<asp:ContentPlaceHolder id="init" runat="server"></asp:ContentPlaceHolder>
<head runat="server">
<asp:ContentPlaceHolder ID="title" runat="server">
<title><%=this.Page.Title%></title>
</asp:ContentPlaceHolder>
</head>
View Page
Could either override the entire "title" content placeholder:
<asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server">
<title>Home Page</title>
</asp:Content>
or programatically set the page title.
<asp:Content ID="Content1" ContentPlaceHolderID="init" runat="server">
<%this.Title = "Home Page";%>
</asp:Content>
Make sure you remove the Title="" from the Page directive at the top, or you won't be able to programatically change Page.Title.
I see a lot of people that use the <%= ViewData["Title"] %> option.
I suppose you could also insert a ContentPlaceHolder named Title and then just use that on your page, but in all the MVC examples I've seen, they use the first option.
When I create a new MVC project it has files in there and uses a master page. Looking at that it seems it passes the title to the ViewData as ViewData["Title"] and in the master page, in the <head> there is a script block that outputs ViewData["Title"].
I ended up using a code-behind file to implement Page.Title="..." in the Page_Load() method.
I didn't like doing this, however attempts to implement the change directly in the .aspx page did not work, as it resulted in two <title> tags being present, the one I generated, and the one generated by the Master file the page inherited from.
Ideally, my page code should have overridden the master file's <title> value, but I guess this is just one of those quirks that ASP.Net MVC still has, and one that may already be fixed in a newer version of the ASP.Net MVC Framework (we're still on ASP.Net MVC Beta)
You could do this in your Master Page:
<title>
<%:MyTitle + " :: " %>
<asp:ContentPlaceHolder ID="TitleContent" runat="server">
</asp:ContentPlaceHolder>
</title>
where MyTitle = some value from your web.config or hard text like "My Web"
Now in the view pages (Index for example):
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
<%:"My Home Page"%>
Now when you browse your home page, the title would be "My Web :: My Home Page".
I have a base view class that sets the page title from a resource file. Works pretty good for me.
I created a class called Application with a Title property (using get/set):
public static class Application
{
static string title;
public static string Title
{
get { return title; }
set { title = value; }
}
}
I then set the property on the Page_Load event for each page:
Application.Title = "Silly Application";
then i just reference that property on the master page:
<div id="divApplicationTitle">
<asp:HyperLink runat="server" NavigateUrl="~/Default.aspx"><asp:Image ID="imgApplicationImage" runat="server" SkinID="skinApplicationLogo" /><%=Application.Title%></asp:HyperLink>
</div>
There is a Title property of the #Page directive for content pages.
For ASP.NET content pages just add Title="" in the <%# %> Placeholder.
We ended up with
<head runat=server visible=false>
in master page.
This way we can read from Page.Title (Page.Title requires head element to exist, otherwise it throws an exception, checked that with reflector). We then use our own head element - MVC way.
You could always use javascript in your view page:
<script type="text/javascript>
document.title = "Hello World";
</script>

Resources