Getting Child page title from user control on Master page - c#

I have a user control in the Master page. In the code behind of that ascx, I want to get the title of the page. The title is being set in the head section with tag in the child pages.

Try this
var obj = this.Parent.Page;
var title= obj.Title;

Have you tried Page.Title?
However, I think the head tag needs to be ran server side to use this

I would think Page.Title would be enough. If not, you have to ride up through the object model a bit until you get to the page. Both solutions have been detailed above. The only variation may be if the ascx is set on the master page rather than the page. Worst case here is getting the title in the master page and feeding to the ascx as the page is rendered.
Now, an understanding of why this gets a bit confusing. Most people think the page sits on the master page. But, technically, the master page is set up as a control on the page. This is largely to avoid a complete rearchitecture of ASP.NET as master pages were introduced. This means the page is requested and starts to render. Then the master page linked tags are hit and that "control" is rendered, etc. In some cases, Microsoft has provided easy short cuts, in others, you have to navigate and the navigation is upside down from many people's expectation.

Related

ASP.net not posting back to correct page

So I have a slightly unorthodox application type.
I have an aspx page called AddNewBlog.aspx. This page generates XML data from database queries and it include the file AddNewBlogXSL.aspx which is an xsl style sheet.
The effect is that the AddNewBlog XML data is transformed by AddNewBlogXSL on the client side into XHTML.
So although the requested page is AddNewBlog.aspx, the layouts and controls and forms are on AddNewBlogXSL.aspx since it contains all the layout and formatting.
When on AddNewBlogXSL.aspx I do an asp:button it tries to post back to AddNewBlogXSL.aspx as is understandable.
The problem is that page is an xslt stylesheet not a webpage.. I need it to post back to AddNewBlog.aspx as this is the proper page which includes AddNewBlogXSL.aspx
The only thing I seem to be able to do is allow the default behaviour which is to submit to AddNewBlogXSL.aspx, process the page, and redirect them to the proper page AddNewBlog.aspx but then it makes it hard to handle error messages and such since I have no control over AddNewBlog.aspx after I have simply redirected to it from AddNewBlogXSL.aspx
Any ideas at all?
You are looking for PostBackUrl property.
<asp:button id="Button2"
text="Post value to another page"
postbackurl="~/Path/To/AddNewBlog.aspx"
runat="Server">
</asp:button>
EDIT:
To address your comment, IsPostBack will not be true in this scenario because it isn't a postback, it's just a post to another page. You have to access the values via the Page.PreviousPage property as outlined in the MSDN article I listed.
During a cross-page postback, the contents of the source page's controls are posted to the target page, and the browser executes an HTTP POST operation (not a GET operation). However, in the target page, the IsPostBack property is false immediately after a cross-page post. Although the behavior is that of a POST, the cross-posting is not a postback to the target page. Therefore, IsPostBack is set to false and the target page can go through its first-time code.
Also per MSDN, you would check the PreviousPage.IsCrossPagePostBack property instead of the Page.IsPostBackProperty
if(PreviousPage.IsCrossPagePostBack == true)
{
//Get values from PreviousPage
text = ((TextBox)PreviousPage.FindControl("TextBox1")).Text;
}
Cross Page Posting Details
I went ahead and wrote a little test harness (aka, I took the example off the MSDN page, :-0 )to verify and results are as follows when cross page posting:
It's not an ideal situation and it kludgey to access your values as listed, but for the model you have designed, it's the best I can think of.
In addition to the above answer, Can you please confirm that the "AutoEventWireUp" is false in this page. If so, override the page load method in this case.

Page Title from a User Control possible?

I have a Search.aspx page which calls UCSearch control. UCSearch control does everything like getting what is being searched and what should be displayed, etc. I am trying to give the title to the page. As i dont have any info to write the code in the aspx page, i am thinking to write it in the control. But it is not displaying me when i tried using Page.Title in control. What am i doing wrong?? This is in Asp.net and C#.
Page.Title = "Search Results for Newark, NY";
Thanks in advance!!
Does not:
this.Page.Title = "My beautiful title";
work?
You should be able to get to the ASPX using the Parent property of the control. Cast that property to a Page (it's a WebControl or something similarly generic), then set its Title property. If you have a hierarchy of master pages or are nesting this control in other controls, you may need to traverse the Parent hierarchy for a few more levels.
You could also fire an event from your user control, passing the Title that you would like to display. You could then handle this event on the page, and set the title.
This does require a small amount of code in your aspx page, however, at least now the user control does not care where the title goes, the parent of the control can worry about it. If ever you want to change where this title goes, or even put it in multiple places, you don't have to change the user control. Let me know if you want a sample, I'll add it.
If you don't like that idea, then cederlof's answer will work, I just tested it.
protected void helloBtn_Click(object sender, EventArgs e)
{
this.Page.Title = "hello from control";
}
** You can use naming container to find the parent control of the current control. Through this way you can move through the page hierarchy.
Quickwatch will help you a lot in figuring out the things and building the statement for quick casting. Do some more research on naming container.
var container = userControl.NamingContainer;
if(container is Page)
{
Page p = container as Page;
p.Title = "Your Title";
}
**
Above is not the exact solution, but can help you it you can usercontrol directly on the page. Unless you need to iterate through the page controls. This was just for an quick help.

Can I know what page is in my master page's ContentPlaceHolder?

All the Google finds I ran into tell me how to use FindControl to access a control on the master from the content page itself.
However, what I'm trying to do is the opposite.
From the master page, I want to reference whichever child page is in the ContentPlaceHolder.
Why you ask.
I want the master page to know which tab should be active depending on the content Page currently in the placeholder.
This lets me avoid having each page to reference the master page and allow them to change the active tab; that should be the master page's job (if there's a way it can know whom it's enclosing).
Thanks. No rants please.
If you are looking to get the instance of the executing page class, you can retrieve it from the current HTTP context:
var page = HttpContext.Current.CurrentHandler as Page;
From there, you can navigate the page's control tree, call FindControl(), and so on. Be cautious about page lifecycle, though, as master page events tend to fire before their page event counterparts.

How masterpage get the current page from masterpage by itself

I am writing a website with Visual Studio 2008, C# 3.5 and ASP.NET MVC 2. I put the navigation bar in the masterpage.But there is problem that I will not know which button is needed to be highlight(current page) in the navigation bar.
I want get the current page that need to be highlight by masterpage self (not through the content page).And I don't think it is a good way to get the current page by url string.Because I have no idea about the final url is.
So how can I do this?
I guess you could set a ViewData["currentPage"] value in the Action methods, this would allow you to process that ViewData in the Masterpage. That is, however, off the top of my head and I'm sure there's a more elegant way to do this.
When you click the link in the navigation bar (in the master page) that should be triggering a controller action that will decide which view content page will be shown. In that action method you can (as Lazarus suggests) add some data identifying the current page to ViewData that will be picked up by the master page to modify the navigation bar.

Element-Enhancing Javascript in ASP.NET Master Pages

I have run in to a bit of a problem and I have done a bit of digging, but struggling to come up with a conclusive answer/fix.
Basically, I have some javascript (created by a 3rd party) that does some whizzbang stuff to page elements to make them look pretty. The code works great on single pages (i.e. no master), however, when I try and apply the effects to a content page within a master, it does not work.
In short I have a master page which contains the main script reference. All pages will use the script, but the parameters passed to it will differ for the content pages.
Master Page Script Reference
<script src="scripts.js" language="javascript" type="text/javascript" />
Single Page
<script>
MakePretty("elementID");
</script>
As you can see, I need the reference in each page (hence it being in the master) but the actual elements I want to "MakePretty" will change dependant on content.
Content Pages
Now, due to the content page not having a <head> element, I have been using the following code to add it to the master pages <head> element:
HtmlGenericControl ctl = new HtmlGenericControl("script");
ctl.Attributes.Add("language", "javascript");
ctl.InnerHtml = #"MakePretty(""elementID"")";
Master.Page.Header.Controls.Add(ctl);
Now, this fails to work. However, if I replace with something simple like alert("HI!"), all works fine. So the code is being added OK, it just doesn't seem to always execute depending on what it is doing..
Now, having done some digging, I have learned that th content page's Load event is raised before the master pages, which may be having an effect, however, I thought the javascript on the page was all loaded/run at once?
Forgive me if this is a stupid question, but I am still relatively new to using javascript, especially in the master pages scenario.
How can I get content pages to call javascript code which is referenced in the Master page?
Thanks for any/all help on this guys, you will really be helping me out with this work problem.
NOTES:
RegisterStartupScript and the like does not seem to work at any level..
The control ID's are being set fine, even in the MasterPage environment and are rendering as expected.
Apologies if any of this is unclear, I am real tired so if need be please comment if a re-word/clarification is required.
Put a ContentPlaceHolder in the head section of the master page, then add a asp:Content control on the content page referring to the placeholder and put your script in that control. You can customize it for each page this way.
Also, the reference by ID may not be working because when you use Master Pages, the control IDs on the page are automatically created based on the container structure. So instead of "elementID" as expected, it may be outputting "ctl00_MainContentPlaceHolder_elementID" View your source or use firebug to inspect your form elements to see what the IDs outputted are.
Isn't it possible to do with clean javascript ?-)
-- just add something similar to this inside the body-tag:
<script type="text/javascript">
window.onload = function(){
MakePretty("elementID");
}
</script>
By the way the script-tag has to have an end-tag:
<script type="text/javascript" src="myScript.js"></script>
Why not use jQuery to find all the controls? Something like this:
$(document).ready(function(){
$("input[type='text'], input[type='radio'], input[type='checkbox'], select, textarea").each(function(){
MakePretty(this);
});
});
This way you'll get all elements on the page, you can wait until the page is ready (so you don't modify the DOM illigally). The jQuery selector can get the elements in a bit more of a specific format if you need (ie, add a root element, like the ID of the body div).
It'd also be best to modify the MakePretty method so it takes the element not the ID as the parameter to reduce processing overhead.
Once you use Master Pages, the ids of controls on the client side aren't what you think they are. You should use Control.ClientID when you generate the script.
When using master pages, you need to be careful with the html attribute ID, since .NET will modify this value as it needs to keep ids unique.
I would assume your javascript is applying css styles via ID, and when you are using master pages the ID is different than what is in your aspx. If you verify your javascript is always being added, your answer needs to take into account the following:
ALWAYS set your master page id in page load (this.ID = "myPrefix";)
Any HTML element in your master page will be prefixed by the master page id (i.e.: on the rendered page will be "myPrefix_myDiv")
Any HTML element in your content place holder id will be prefixed with an additional prefix (i.e. myPrefix_ContentPlaceHolderId1_myDiv)
Please let me know if I can clarify anything. Hope this helps!

Categories