Get value from Master Page into class - asp.net

I ve a masterpage(myMaster) where I ve a variable(lets call is myInteger) I want to access in an external class.
Usually I just do that in my aspx: <%# MasterType VirtualPath="myMaster.master" %>
And then I can access to it in my code behind doing: Master.myInteger ...
My issue here is I want to access it in another class(where there is no .aspx)
I tried doing
Master.MasterPageFile = "~/myMaster.master"
Master.AppRelativeVirtualPath = "myMaster.master"
but then Master.myInteger isnt recognized.
I'm not sure what I want to do is possible... Any idea to get this variable?

So you need to reference a MasterPage's property from a class that does not inherit from Page?
I would recommend to use a property or constructor to initialize this class with this value. But if you really need it this way, you can try following approach which uses HttpContect.Current.Handler:
// works even in static context
static void foo()
{
int myInteger = -1;
var page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page;
if(page != null) myInteger = ((myMaster)page.Master).myInteger;
}
Note that this is prone to errors and also hard links your class with a MasterPage.

From an external class, try something like this:
var page = HttpContext.Current.Handler as Page;
if (page != null)
{
var value = ((MasterPageName)page.Master).SomeProperty;
}
If you don't have access to the master page from the external class, you can use reflection to access a property or method:
var page = HttpContext.Current.Handler as Page;
if (page != null)
{
var value = page.Master.GetType().GetProperty("SomeProperty").GetValue(page.Master, null);
}

Related

How to render html code with asp.net class

I need to be able to add a dynamic html code to a random cshtml page using my class:
public class HTMLRenderClass
{
//--here I generate html code
public void RenderControll()
{
LiteralControl ControlGroup = new LiteralControl();
ControlGroup.Text = "<h1>Here will be html code generated above</h1>";
Page p = HttpContext.Current.Handler as Page;
if (p != null) p.Controls.Add(ControlGroup);
else { throw new UserFriendlyException("Page still null"); }
}
}
so that inside cshtml I could call it like
#{
HTMLRenderClass c = new HTMLRenderClass();
c.RenderControll();
}
But the problem is that I don't know how to add my html to the page I need, because "HttpContext.Current.Handler as Page" is always null. Are there any solutions of that situation in which I still could use c.RenderControll() method without passing any "Page object" parameters?
If not, then what exactly should I pass to my class to place my dynamic html block inside static one?

Adding User controls on runtime - accessing the controls

I'm trying to add some user controls on a page. Thats easy, I just do it like this.
UserControl block = (categoryblock) LoadControl("categoryblock.ascx");
Panel1.Controls.Add(block);
But i want to access the label controls and more that are inside the categoryblock.ascx.
How would i do that ?
I cant do it like this,
block.l_itemName.text = "blabla";
I managed to user FindControl("l_itemName") but i would rather like to have the intellisense.
create following property in your user control:
public string ItemName() {
get() {
return l_itemName.text;
}
set(String value) {
l_itemName.text = value;
}
}
This will make you able to do block.ItemName = ""or string temp = block.ItemName
I hope this will help

ASP.NET MVC2: modifying master css property depending on query string parameter

I am migrating a web site to a new one using ASP .NET MVC2.
In the original site, master page has code-behind to check a query string parameter value. Depending on this value, code-behind dynamically modify some CSS property to hide / display master page elements.
As MVC2 has no code-behind because we are supposed to perform everything in the controllers, how should I proceed in this case ?
I see this : asp.net mvc modifying master file from a view
It partially answers my needs but the query string processing is common to all pages. How can I move this processing in a common code section ?
Regards.
A helper method looks like a good place:
public static class HtmlHelperExtensions
{
public static string GetCss(this HtmlHelper htmlHelper)
{
// read some request parameter
// here you also have access to route data so the
// parameter could be part of your custom routes as well
var foo = htmlHelper.ViewContext.HttpContext.Request["foo"];
// based on the value of this parameter
// return the appropriate CSS class
return (foo == "bar") ? "barClass" : "fooClass";
}
}
And somewhere in your master page:
<body class="<%= Html.GetCss() %>">
Or if you are always going to apply it to the body tag only it might be more appropriate to do this in order to reduce the tag soup:
public static class HtmlHelperExtensions
{
public static MvcHtmlString StartBody(this HtmlHelper htmlHelper)
{
var body = new TagBuilder("body");
var foo = htmlHelper.ViewContext.HttpContext.Request["foo"];
var bodyClass = (foo == "bar") ? "barClass" : "fooClass";
body.AddCssClass(bodyClass);
return MvcHtmlString.Create(body.ToString(TagRenderMode.StartTag));
}
}
and in your master page at the place of the body tag:
<%= Html.StartBody() %>
I can think of two solutions to this:
Derive your controllers from one controller base and set the ViewData parameter there depending on posted Form values
Don't use ViewData at all, but simply look for the form value in the view (using HttpContext.Current)
The second method violates the MVC pattern. IMO it is still acceptable in some scenarios, for example I am using this approach to highlight the currently selected item in a navigation menu.

How do I set the StripFormattingOnPaste property of a Telerik RadEditor with JavaScript?

I don't have access to the actual asp.net server tag itself, so I need to change the StripFormattingOnPaste property to the EditorStripFormattingOptions enum with JavaScript and I'm not sure how. I have some code that adds an OnClientLoad() and OnClientCommandExecuted() functions that works so I can add it in there, I'm just not sure where the property exists on the client-side and what the enum value would be:
// init OnClientLoad and OnClientCommandExecuted event handlers for all radeditors on the page
Sys.Application.add_load(function() {
if (typeof ($telerik) != "undefined") {
if ($telerik.radControls && Telerik.Web.UI.RadEditor) {
for (var i = 0, l = $telerik.radControls.length; i < l; i++) {
var control = $telerik.radControls[i];
if (Telerik.Web.UI.RadEditor.isInstanceOfType(control)) {
var editor = control;
// ??? editor._stripFormattingOptions = Telerik.Web.UI.StripFormattingOptions.NoneSupressCleanMessage
// editor already loaded, fire event
OnClientLoad(editor);
// attach event handler for paste commands
editor.add_commandExecuted(function(ed, args) {
return OnClientCommandExecuted(ed, args);
});
}
}
}
}
});
Update: I've discovered that the correct enum setting that I want is Telerik.Web.UI.StripFormattingOptions.NoneSupressCleanMessage.
Update #2: I see that the RadEditor JS object has a _stripFormattingOptions property, but I think it might just be for private use.
The Telerik controls are based on ASP.NET AJAX and use pretty much the same coding conventions - public properties have getters and setters methods. In this case you should use
editor.set_stripFormattingOptions(Telerik.Web.UI.StripFormattingOptions.NoneSupressCleanMessage);
To get the current value, use
var value = editor.get_stripFormattingOptions();
The property you saw (editor._stripFormattingOptions) is just used to store the value. Since its name starts with an underscore you are correct to assume that it is private and so you should not rely on it. The getter and setter methods are public and you are free to use them.

Is there a System.Web.UI.ClientScriptManager method that registers scripts inside the <head> tag?

I know it's strictly OK to put <script> tags in the body, but in the interest of neatness I'd like to use System.Web.UI.ClientScriptManager to register a script in the <head> of my page. Is there a method to accomplish this?
Thanks in advance.
In these cases I usually add a ContentPlaceHolder in the tag of my Master Page.
Alternately I've used a method (usually in a utility class or PageBase class) that puts the script string in a List and stores it in the ASP.Net Context like so:
List<string> javaScriptUrls = new List<string>();
url = url.ToLower();
javaScriptUrls = Context.Items[JS_KEY] as List<string>;
if (javaScriptUrls == null)
{
javaScriptUrls = new List<string>();
javaScriptUrls.Add(url);
}
else
{
if (!javaScriptUrls.Contains(url))
javaScriptUrls.Add(url);
}
Context.Items[JS_KEY] = javaScriptUrls;
Then OnPreRender of the MasterPage, it reads this List from the Context and builds tags in the header.
List<string> _javaScript = Context.Items[JS_KEY] as List<string>;
foreach (string js in _javaScript)
{
HtmlGenericControl script = new HtmlGenericControl();
script.TagName = "script";
script.Attributes.Add("type", "text/javascript");
if (js.StartsWith("~/"))
script.Attributes.Add("src", head.ResolveUrl(js));
else
script.Attributes.Add("src", js);
head.Controls.Add(script);
AddHeaderLineBreak(head);
}

Resources