Adding attribute to master page usercontrol from content page? - asp.net

I have a usercontrol for header in the masterpage. I need to an attribute 'linkName' from some of the content pages. ie for some pages it should be
<uc1:AdminHeader ID="Adminheader1" runat="server" linkClass="adminHeaderSelected" link="manageData"></uc1:AdminHeader>
and in few other pages it should be
<uc1:AdminHeader ID="AdminHeader1" runat="server" linkName="adminusers"></uc1:AdminHeader>
how can i acheive this througn content pages?

Add a public property LinkName to your MasterPage that get/set the UserControl's property.
Then you can set it from the page in the following way:
((MyMaster)this.Page.Master).LinkName = "adminusers";
Where MyMaster is the actual type of your MasterPage.
VB.NET:
DirectCast(Me.Page.Master, MyMaster).LinkName = "adminusers"
Edit: If you want to add an non-existing attribute at runtime:
Create a method AddHeaderAttribute:
public void AddHeaderAttribute(string key, string Value)
{
Adminheader1.Attributes.Add(key, Value);
}
VB.NET
Public Sub AddHeaderAttribute(key As String, Value As String)
Adminheader1.Attributes.Add(key, Value)
End Sub
Call this method in the way described above, for example
((MyMaster)this.Page.Master).AddHeaderAttribute("LinkName", "adminusers");
http://msdn.microsoft.com/en-us/library/system.web.ui.usercontrol.attributes.aspx

Related

How to access master page public property from a NESTED content page

After exposing a public property in Top.Master it can be accessed in any child page that has a master type reference on its page.
How can the same properties be accessed from a nested page?
I tried to cascade the properties down the heirarchy but the child page errors when trying to access it.
I would prefer to access the exposed top.master property directly from the nested content page but am unsure of a good way to do this.
TOP.MASTER
<asp:Label ID="lblMsg" ClientIDMode="Static" runat="Server" />
TOP.MASTER.VB
Partial Public Class TopMaster
Inherits MasterPage
Public Property Msg As String
Get
Return lblMsg.Text
End Get
Set(value As String)
lblMsg.Text = value
End Set
End Property
End Class
CHILD.MASTER
<%# MasterType VirtualPath="~/Top.Master" %>
CHILD.MASTER.VB
Master.Msg = "Success"
CHILD.PAGE
<%# MasterType VirtualPath="~/Child.Master" %>
CHILD.PAGE.VB
Master.Master.Msg = "Success"
In your child.master class you can create a Msg property that would proxy the top master Msg property
You can add the following code in child.master.vb
Public Property Msg As String
Get
Return Master.Msg
End Get
Set(value As String)
Master.Msg = value
End Set
End Property
then in your child.page.vb you can access this property doing
Master.Msg = "Success"

C# ASPX: How to get a Parent page's inherited property in a Control?

I have an aspx page that inherits a master page which has a protected property. Like this:
masterpage
{
protected string propX..
}
MyPage : masterpage
---myControl:UserControl
In myControl code-behind I'd like to access propX
Any ideas?
Thanks!
Maybe try to cast the Page property of myControl class to MyPage class?
string value = ((MyPage)this.Page).propX
And if you want to access this property from other class (like myControl), the access modifier of property propX should be set to internal or public
I've assumed, that you've placed myControl object on MyPage page.
You could possibly change the access modifiers for the string. Maybe set it to internal.
Are you sure you're inheriting from the master page? Adding the MasterPage directive doesn't mean that it inherits from it. Usually an aspx page should directly or indirectly inherit from System.Web.UI.Page.
The master pages aren't "inherited" which means that protected members cannot be accessed from the page class (or control class). Your best option is to make the property public or internal.

Asp.net user control with inner controls

I need to develop a template-like user control, which would accept any arbitrary content, including other controls.
WmlCard.ascx
<asp:PlaceHolder ID="phContent" runat="server">
<card id="<%= Me.CardId %>" title="<%= Me.Title %>">
<p>
<%= Me.InnerText %>
</p>
</card>
</asp:PlaceHolder>
It would be used this way:
ListaTelefonica.aspx
<%# Register TagPrefix="sic" TagName="Card" Src="~/path/to/WmlCard.ascx"%>
<sic:Card ID="BuscaCard" runat="server" CardId="busca" title="Lista TelefĂ´nica" Visible="false">
<asp:Literal ID="SomeLiteral" runat="server" Visible="false">Some text<br /></asp:Literal>
<asp:Literal ID="RuntimeFilledLiteral" runat="server" Visible="false" /><br /></asp:Literal>
Any text.
</sic:Card>
It is unfortunate that Ascx user controls have to inherit System.Web.UI.UserControl. If I could inherit System.Web.UI.WebControls.WebControl, for example, it would be a piece of cake.
My problem is similar to this one, but instead of just text the control should accept any other control inside it.
I tried <ParseChildren(False)> and overriding AddParsedSubObject(Object) in WmlCard, but it is not a solution because the html is rendered before the Page Load, making it pointless to change the value of RuntimeFilledLiteral.Text in a page's Page_Load, for example.
First error I got:
Parser Error Message: Type 'ASP.sic_sicphone_usercontrol_wmlcard_ascx' does not have a public property named 'Literal'.
After adding <PersistenceMode(PersistenceMode.InnerDefaultProperty), ParseChildren(True, "InnerText")>:
The 'InnerText' property of 'sic:Card' does not allow child objects.
Same as above but changing WmlCard's property InnerText type from String to List(Of Object):
Literal content ('Any text.') is not allowed within a 'System.Collections.IList'.
After adding <ParseChildren(False)> and overriding AddParsedSubObject:
No error message, but WmlCard's content is rendered to html before I have a chance to change its inner controls runtime properties.
If I change WmlCard to inherit System.Web.UI.WebControls.PlaceHolder instead of System.Web.UI.UserControl:
'...UserControl.WmlCard' is not allowed here because it does not extend class 'System.Web.UI.UserControl'.
Found a valid way:
1) Put nothing inside my control (WmlCard.ascx).
2) Added the attribute <ParseChildren(False)> to WmlCard.
3) Added a handler to the event PreRender on WmlCard:
Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
Dim litBefore As New Literal()
litBefore.Text = String.Format("<card id=""{0}"" title=""{1}""><p>", Me.CardId, Me.Title)
Dim litAfter As New Literal()
litAfter.Text = "</p></card>"
Me.Controls.AddAt(0, litBefore)
Me.Controls.Add(litAfter)
End Sub
And that's it. Everything is working. Thanks for your help thinking thru this!
What you need is a templated user control.
Take a look at this article for a detailed how-to: http://msdn.microsoft.com/en-us/library/36574bf6.aspx.
Actually you could create a custom user control, inherit from placeholder and your problem should be solved?
You can go the templated control way as suggested but I don't see the reason why you would want to do that.
[SupportsEventValidation, DefaultEvent("YourEventName")]
[ParseChildren(true)]
[PersistChildren(false)]
[ToolboxBitmap(typeof(System.Web.UI.WebControls.Panel))]
public class MyCustomControl : System.Web.UI.WebControls.PlaceHolder, INamingContainer, IPostBackDataHandler, IPostBackEventHandler
you can override the Render method to control the rendered HTML. I am struggling to see youru actual problem.
Got this working simply enough.
[ParseChildren(false)]
public class CssControl : System.Web.UI.UserControl
{
protected override void Render(HtmlTextWriter writer)
{
string html = null;
using(var innerWriter = new System.IO.StringWriter())
using(var htmlWriter = new HtmlTextWriter(innerWriter))
{
base.Render(htmlWriter);
html = innerWriter.GetStringBuilder().ToString();
}
var min = ScriptAndCssParser.MinifyCssFromHtml(html);
writer.Write(min);
}
}
In my case my goal was allow a master page level control to have child HTML and server-controls, like asp:content blocks. That way Viewpages could pass stylesheets up the chain to the master page.
Then I wanted to intercept all the generated HTML, and minify the CSS files. The minification part is out of scope for this question, but the above ParseChildren(false) prevents the "element can't contain..." error in the .aspx, and then calling base.Render() on an inner writer allows you to use the existing Web Forms pipeline to do all the rendering for you of both server-controls and plain HTML content.

Can I hide a user control in a master page from a content page?

How can I hide a user control on the master page from a content page? This is code I have on my content page's load.
Dim banner As UserControl = DirectCast(Master.FindControl("uc_banner1"), UserControl)
banner.Visible = True
Does nothing for me :(
Expose the visible property of the user control via a property of the MasterPage.
In your MasterPage:
public bool MyBannerVisibility
{
get { return uc_banner1.Visible; }
set { uc_banner1.Visible = value; }
}
Then make sure to add a reference in your content page:
<%# MasterType TypeName="YourMasterPageTypeName" %>
Then in your content page just do:
Master.MyBannerVisibility = false;
Edit: Since your using VB.net I used a code converter to convert it for you:
Public Property MyBannerVisibility() As String
Get
Return uc_banner1.Visible
End Get
Set
uc_banner1.Visible = value
End Set
End Property
Content Page:
Master.MyBannerVisibility = False

asp.net use class object on form

I am creating an object at server side of an aspx (test.cs) page from a class (asp.net 2.0 C#)
public partial class Vendor_VendorUsedTicketsPopup : System.Web.UI.Page
{
ReportInvoice _objReportInvoice = new ReportInvoice();
protected void Page_Load(object sender, EventArgs e)
{
_objReportInvoice.ReportId = 1;
}
}
as you see above before Page Load I am creating a new ReportInvoice object and on page load I am setting property ReportId to 1
On test.aspx I want to use the ReportId value bu using the _objReportInvoice object like below
<div><% _objReportInvoice.ReportId; %></div>
But when I build the site I get the error
The name '_objReport' does not exist in the current context
I know that I can create a public integer for ReportId above Page_Load and use it on aspx page. That works fine , but I want to use class object properties on aspx page.
What is the way of doing sth like that ?
Thanks...
You need a = sign in there to print it to the page:
<div><%= _objReportInvoice.ReportId; %></div>
However, I would suggest just using a Literal or Label control there and then setting it's text to the ReportID property in the code behind. Inline code like that can make your HTML messy.
Remember that your .ASPX markup page inherits from the codebehind class.
This means that unless you declare your field as protected or public, the .aspx will not have access to your field.
You need to add an access modifier to your field to make it non-private.

Resources