.net templates which page am I on? - asp.net

I'm curious to know that using .net 2.0 with a master page if there is a way that I can pick up what page I am on so that i can use it to style a tab?
My master page has a nav bar on it, and what I wan to do is:
If the user is, say on the contact page, that the tab for the contact page would be a different color, can this be achieved. I have seen some examples that don't use master pages and of course you can use the encapsulating body tag to signify where you are but this isn't available with a masterpage.
Thanks R.

MasterPage though the name sound otherwise behaves like a child to a page that uses it.
Think of it as a UserControl to a page. You can actually access to the Page instance and it's Request property.
Here's an example on how you can use it
switch(Request.Path){
case "/page1/aspx":
//dosomething to your tabs
break:
case "/page1/aspx":
//dosomething to your tabs
break:
.
.
.
default:
//dosomething else
.
.
.
}

If you want to change the content on the masterpage from the page (i.e. change the tab color) you should:
In the masterpage, publicly expose a property or method that will change the color of the tab.
i.e.:
public void changecolor(string PageName, string Color){
switch(PageName){
case "home":
this.TabHome.Color=Color;
}
}
Then put a directive at the top of the aspx page with the masterpage path. Like such:
<%# MasterType VirtualPath="~/Site.master" %>
Once this is done, from the codebehind, you can access the masterpage and see its exposed method, then just call this and you're done.
protected void Page_Init(object sender, EventArgs e){
Master.changecolor("home", "red");
}
this way, you won't have to parse pagenames and deal with the maintenance that comes when you try to change the name of the page etc. you will also limit your case statement to the number of tabs, and not the number of pages in your site.

Create the following method in your masterpage (or helper class) and then add a reference to it in your Page_Load method in the masterpage:
public string GetCurrentPageName()
{
Uri uri = Request.Url;
string[] uriSegments = uri.Segments;
string pageName = "";
if( 0 < uriSegments.Length )
{
pageName = uriSegments.Last();
}
return pageName;
}
}
That should give you the current filename - you might want to strip out the ".aspx" part of the filename also. I haven't tested this with a QueryString yet so not sure if Last() still returns the filename in that case.
If your tabs are asp.net controls, you can use FindControl() to find the tab - you'll need to match your tab ids with your page names of course. Once you have the control you can add a "selected" style in code-behind.

Related

Initialize Session in Masterpage: 'subpage' problem

I'm having a hard time with the page cycles when using masterpages and contentpages.
My masterpage has two linkbuttons that are used to select a language (using resources). When these buttons are clicked I create Session["language"].
The goal I have is to 'translate' my masterpage after the buttons are clicked AND to translate the content page.
I've been trying all kinds of different methods (Page_Load etc) based on this url: http://msdn.microsoft.com/en-us/library/dct97kc3.aspx but it never works like it should. Usually the content page only gets translated after two clicks. I can't figure out the cycle problem between the masterpage and the content page combined with the click-events.
Any suggestions?
Thank you.
I used to do this by overriding InitializeCulture method in the master page. The language code is passed via query-string:
protected override void InitializeCulture()
{
if (!string.IsNullOrEmpty(base.Request["language"]))
{
System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture(base.Request["language"]);
System.Threading.Thread.CurrentThread.CurrentCulture = culture;
System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
}
}
And the link will look like the following:
Vis på Dansk
Don't forget to validate an input value first :-)

How to get past embedding a html form for paypal buttons asp.net

I have some experience of using paypal with an asp.net website, however this issue has me really stumped.
Root of the problem: You cant embed the html form for the paypal button inside your page form.
Original solution: Originally my website was using multiple aspx pages so I could simply arrange my form tags so that they weren't embedded inside one another.
My website now uses a master aspx page which draws in different ascx controls. This means that I do not have the option of arranging the form tags around the page so need a work around.
NB. I have looked all over the place for simple solutions but it is a jungle out there, paypal is a nightmare. I did find something on ghost form which is all in c#. Might help...
Thanks in advance for any help....
Submit the PayPal information using their APIs rather than submitting a form directly to them.
That way you can keep everything as part of a single form and add a little more robustness around the PayPal input and validation.
PayPal: SDKs and Downloads
Had this issue with another payment provider also. You could either use their API, or you could work around it by:
Making the checkout button a standard imagebutton
Running something like ClientScript.RegisterStartupScript() to output both HTML and Javascript. The HTML should be the actual form with all hidden fields and proper id. The javascript is code which would execute on page load and submit the page.
i.e. ClientScript.RegisterStartupScript(Me.GetType(), "PaypalSubmit", "<AllMarkUp><GoesHere><script>And.Javascript</script>", False)
Hope this helps, otherwise you could use the web service API. By taking this approach you are performing a postback, outputting the HTML form (outside the .NET form because it is at the bottom of the page) and then relying on the javascript to actually submit it.
Here's something that will work for you. In your code-behind:
// Workaround for PayPal form problem
CustomForm mainForm = new CustomForm();
mainForm.RenderFormTag = false;
Create a custom form class which overrides the HtmlForm class:
public class CustomForm : System.Web.UI.HtmlControls.HtmlForm
{
protected bool _render;
public bool RenderFormTag
{
get { return _render; }
set { _render = value; }
}
public CustomForm()
{
//By default, show the form tag
_render = true;
}
protected override void RenderBeginTag(HtmlTextWriter writer)
{
//Only render the tag when _render is set to true
if (_render)
base.RenderBeginTag(writer);
}
protected override void RenderEndTag(HtmlTextWriter writer)
{
//Only render the tag when _render is set to true
if (_render)
base.RenderEndTag(writer);
}
}

Can I create custom directives in ASP.NET?

I have created a menu control in asp.net and have put it into master page. This menu control have property ActiveItem which when modified makes one or another item from menu appear as active.
To control active item from child page I have created a control which modifies master page property enforced by IMenuContainer interface to update menu control's active item in master page.
public class MenuActiveItem : Control
{
public ActiveItemEnum ActiveItem
{
get
{
var masterPage = Page.Master as IMenuContainer;
if (masterPage == null)
return ActiveItemEnum.None;
return masterPage.ActiveItem;
}
set
{
var masterPage = Page.Master as IMenuContainer;
if (masterPage == null)
return;
masterPage.ActiveItem = value;
}
}
}
Everything works perfectly and I really enjoy this solution, but I was thinking that, if I knew how, I would have created a custom directive with same feature instead of custom control because it just makes more sense that way.
Does anybody know how to do it?
You should be able to turn this into a custom property of your Page, which you can set in the Page directive.
Create a base class for your page, and then change your Page directives like this:
<%# Page Language="C#" MasterPageFile="~/App.master"
CodeFileBaseClass="BasePage" ActiveItem="myActiveItem" AutoEventWireup="true"
CodeFile="Page1.aspx.cs" Inherits="Page1" %>
You may have to change the property to be a string, and do a conversion to the enum. But otherwise your code can remain the same, and it doesn't have to be in a control.

Inject Html Into a View Programmatically

I have a tricky problem and I'm not sure where in the view rendering process to attempt this. I am building a simple blog/CMS in MVC and I would like to inject a some html (preferably a partial view) into the page if the user is logged in as an admin (and therefore has edit privileges).
I obviously could add render partials to master pages etc. But in my system master pages/views are the "templates" of the CMS and therefore should not contain CMS specific <% %> markup. I would like to hook in to some part of the rendering process and inject the html myself.
Does anyone have any idea how to do this in MVC? Where would be the best point, ViewPage, ViewEngine?
Thanks,
Ian
You could use Html.RenderPartial to insert an HTML fragment somewhere in the page. If you want to insert it in a place not available to the view but only on the master you could place a <asp:ContentPlaceHolder ID="Admin" runat="server" /> placeholder inside the master and in the view simply override it and insert the partial. If placing such a placeholder is not acceptable you could use AJAX like: $('#adminHolder').load('/home/admin');, but I would probably go with the previous approach as it will work in case the user has javascript disabled.
OK this took a bit of messing and the result is a little hacky. But it works and that's all that matters right....
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
if (!User.Identity.IsAuthenticated || !User.IsInRole("Admin"))
{
// If not admin continue as normal
base.Render(writer);
return;
}
// Taking a leaf out of the move viewstate to the bottom of page playbook
var stringWriter = new System.IO.StringWriter();
var htmlWriter = new HtmlTextWriter(stringWriter);
base.Render(htmlWriter);
var html = stringWriter.ToString();
var endOfBody = html.IndexOf("</body>") - 1;
if (endOfBody >= 0)
{
var adminConsole = Html.RenderPartialAsString("AdminPanel");
html = html.Insert(endOfBody, adminConsole);
}
writer.Write(html);
}
I implement my own ViewPage overriding the Render method. This checks if the user is logged in as an admin and if they are, it renders a partial at the bottom of the page. Very similar to old skool viewstate hacks in webforms.
Enjoy.

Get MasterPage Hiddenfield Value From a User Class

Is there a way to get a value I am storing in a Master Page hidden field from a User Class which I created and placed in the App_Code folder of my ASP.Net 2.0 Application?
Some examples would preferably in VB.Net is highly appreciated.
Thanks.
To give further details, assume the following:
MasterPage.Master
MasterPage.Master.vb
MyPage.aspx
Mypage.aspx.vb
IN the app_code folder, add a new class, say TESTClass.
I have placed some logic in master page. MyPage.aspx uses the Masterpage.master as its master page. In the master page, the logic which I did stores a value into a hidden field.
in my TestClass, how do I access the master page hidden field?
Please take note that TestClass is NOT a user control but a user defined class, which contains some Business-Specific logic which is accessed by myPage.aspx.vb.
I tried ScarletGarden's suggestion but it did not seem to get the Masterpage Hiddenfield which I need to get the value.
Would something like this work?
((HiddenField)this.Page.Master.FindControl("[hidden control id]")).Text
You can get it by these :
hiddenControlValue = HttpContext.Current.Request["hiddenControlId"]
or you can pass your page to your method that belongs to your class under App_Config, and reach it as :
public static string GetHiddenValue(Page currentPage)
{
return currentPage.Request["hiddenValue"];
}
or you can get it over context :
public static string GetHiddenValue()
{
return HttpContext.Current.Request["hiddenValue"];
}
hope this helps.
EDIT: I re-read the question after answering, and realize my answer was probably not quite what you were after. :/
Jared's code might work, but you can also try the following.
In your MasterPage, make the HiddenField a public property, and store the content in the ViewState to make keep it during post backs.
Something like so:
public HiddenField theHiddenField
{
get
{
if (ViewState["HiddenField"] == null)
return null; //or something that makes you handle an unset ViewState
else
return ViewState["HiddenField"].ToString();
}
set
{
ViewState["HiddenField"] = value;
}
}
You then have to add the following to your ASCX-file:
<%# Reference Control="~/Masterpages/Communication.Master" %>
You then access it thusly.
Page mypage = (Page) this.Page; // Or instead of Page, use the page you're actually working with, like MyWebsite.Pages.PageWithUserControl
MasterPage mp = (MasterPage) mypage.Master;
HiddenField hf = mp.theHiddenField;
Sorry if the answer got a bit messy. This is, of course, how to do it in C#, if you want to use VB have a look at this link for the same idea.

Resources