Webforms: how to specify different content for a given masterpage - asp.net

Given this markup in an ascx file :
<div class="DocumentPara">
<%#Eval("Content1").ToString%>
<%#Eval("Content2").ToString%>
</div>
Is there a syntax I can use to chose the display of "Content1" and "Content2" depending of which masterpage is calling?. I.e. :
<div class="DocumentPara">
<%#Eval("Content1").ToString%>
<If masterpage1>
<%#Eval("Content2").ToString%>
</endIf>
<If masterpage2>
<%#Eval("Content3").ToString%>
</endIf>
</div>
Thanks for your help.

Page's masterpage can be accessed via Master property, so to check for a specific masterpage in use you can do something like
if (this.Master is Master1Type)
The if/else syntax is also possible, and will look like this:
<% if (this.Master is Master1Type) { %>
<%#Eval("Content2").ToString%>
<% }
else { %>
<%#Eval("Content3").ToString%>
<% } %>
However that looks dirty to me, and having conditionals likes this inside the page markup is not a common practice. I would suggest defining a function in code behind to deal with masterpages logic, and output necessary value from the data item:
<%# GetContent(Container.DataItem) %>
protected string GetContent(object dataItem)
{
if (this.Master is Master1Type)
{
return Eval("Content2");
}
// etc
}

Related

Structs and Classes not allowed in single page ASP.NET

Lets assume I have a single ASPX file with this:
<%# Page Language="C#" %>
<html>
<body>
<%
int i = 5;
Response.Write(i);
%>
</body>
</html>
After refresh the browser, I see the content of 'i' in the screen.
However, if I wrote that:
<%# Page Language="C#" %>
<html>
<body>
<%
struct S
{
public int i;
}
S a = new S();
a.i = 5;
Response.Write(a.i);
%>
</body>
</html>
I get the error:
Line 18: a.i=5;
CS1519: Invalid token '=' in class, struct, or interface member declaration.
The same happens if I replace the keyword 'struct' by 'class'.
I know the 'codefile' and 'codebehind' types of projects, but I'm curious why can't I declare structs and classes in one single ASPX file, just like in any C# program.
Can someone point me the reasons?
Thank you.
You can do so using a script element with runat=server specified:
<%# Page Language="C#" %>
<script runat=server>
struct S
{
public int i;
}
</script>
<html>
<body>
<%
S a = new S();
a.i = 5;
Response.Write(a.i);
%>
</body>
</html>
The result in doing so is you create a private struct inner to whatever class the ASPX is inheriting from, therefore it will be accessible anywhere on this page (but nowhere else).
Another example: Declare a class in inline-code in aspx/c#
More info about using script embedded code blocks here: https://msdn.microsoft.com/en-us/library/ms178135.aspx#Anchor_0
Because the .aspx page is compiled as a class.
And when you have a code-behind class, you'll notice that it is marked as partial. The .aspx page and its code-behind class are both compiled as partial class with the same name.
I suspect that the contents of the .aspx is placed in a method and you cannot declare structs or classes inside a method.

Response.write to <head>

Hopefully this won't be a difficult question for someone to answer, but I am having a lot of trouble finding the solution online. I am trying to add some HTML to my asp.net page from the code behind (It's VB.net). I would like to add the HTML into the head section of my page but can only add to the body currently.
You can put code in the head, just like the body. For example:
<%= CallAMethodThatReturnsAStringOfHtml() %>
You could try creating a property in your code behind and add your html in the Page_Load method:
Public MyHtml As String
then in the head section of your HTML just use the literal notation:
<%= MyHtml %>
Have runat attribute on your head element and you will be able to access it
<head id="someHead" runat="server">
</head>
Now in your codebehind, you can set it like
someHead.InnerHtml="<script src='somelibrary.js' ></script>";
I made this way, and it worked:
on the .aspx file:
...
<%
Response.Write(GetDisclosureText());
%>
...
on the aspx.cs file:
protected string GetDisclosureText()
{
string disclosure = "";
// ...Apply custom logic ...
if (!string.IsNullOrEmpty(disclosure))
{
return disclosure;
}
return "Error getting Disclosure Text";
}
Note the only difference is that I call Response.Write, not just the function.

Print code behind function return value in aspx page

I'm sure this is trivial, but why isn't the Windows Authentication user printing in my ASP.NET page inline?
Code behind function:
public string GetCurrentUserWindowsLogin()
{
string windowsLogin = Page.User.Identity.Name;
int hasDomain = windowsLogin.IndexOf(#"\");
if (hasDomain > 0)
{
windowsLogin = windowsLogin.Remove(0, hasDomain + 1);
}
return windowsLogin;
}
Inline code:
<div class="loginDisplay">[ <%#GetCurrentUserWindowsLogin() %> ]</div>
The <%#... %> is used for Binding Expressions like Eval and Bind.
So if you call Page.DataBind() in page_load it should work.
Another way that should work is to use code render blocks which run normal code:
<% GetCurrentUserWindowsLogin() %>
or the <%= %> construct used for small chunks of information:
<%= GetCurrentUserWindowsLogin() %>
Just a follow up on the above answer, the <%= is like response.write.
http://msdn.microsoft.com/en-us/library/vstudio/6dwsdcf5(v=vs.100).aspx

strange "" quotes in html before asp.net control

i'm seeing a really strange issue with asp.net rendering. i have EXACTLY this in the relevant part of the .aspx (just replaced names of paths and controls):
<div id="header">
<% if (SiteSettings.SiteName.Equals("sx") || SiteSettings.SiteName.Equals("sw"))
{ %>
<sc:sublayout runat="server" renderingid="{B04CFA1A-6B5B-49D3-8000-339DBE9899C1}"
path="/layouts/AX/HeaderSublayout.ascx" id="AXHeader" placeholder="content"></sc:sublayout>
<% }
else
{ %><!-- bla1 --><ax:strangeBehavingControl id="HeaderInclude" runat="server" IncludeType="Header" /><!-- bla2 -->
<% } %>
</div>
the rendered html looks like:
<!-- bla1 -->
""
expected content from strangeBehavingControl
<!-- bla2 -->
the .ascx for strangeBehavingControl is really simple:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="strangeBehavingControl.ascx.cs" Inherits="layouts.strangeBehavingControl" %>
no extra spaces anywhere, checked already many times. the code behind is also really simple:
public partial class strangeBehavingControl: System.Web.UI.UserControl
{
protected override void Render(HtmlTextWriter writer)
{
var filePath = GetFilePath();
if (!string.IsNullOrWhiteSpace(filePath) && File.Exists(Server.MapPath(filePath)))
Response.WriteFile(filePath);
}
}
so i was thinking that the strange "" where inside the rendered included files, but i checked them manually and they start with the expected characters. any idea how can those characters being inserted there?
You are generating markup for your control incorrectly. Your render method should be using the HtmlTextWriter instance given to it, and not using any direct output writing method on Response.
It also looks like a rather strange setup, as you are writing out the contents as a UserControl, meaning it will be rendered within a page. Is it correct to assume you are always outputting either valid HTML or plain text?
I would suggest you change your Render method as follows:
protected override void Render(HtmlTextWriter writer)
{
var filePath = GetFilePath();
if (!string.IsNullOrWhiteSpace(filePath) && File.Exists(Server.MapPath(filePath)))
using (var sr = new StreamReader(filePath))
writer.Write(sr.ReadToEnd());
}
Sometimes the control file has another charset.
Verify that your file does not have extra characters at the start, and if so remove them.
You may have to use a smart text editor that allows you to do that.
I had the same extra space problem, but my control was not implementing a Render() method.

All controls are still null after calling EnsureChildControls()?

The way this page is laid out, all of the data is loaded at Page_Init. Well, I have a custom control that is having problems with this though.
I have it on the page like so:
<cc:SomeControl... />
And then I set the value at Page_Init using
MyControl.Value="blah";
Simple stuff..
The Value is an accessor and has something similar to this:
public string Value{
get...
set{
EnsureChildControls();
MyHiddenField.Value=value;
}
}
and it is here that I have a problem. It says that MyHiddenField is null. Is Page_Init just too early for this? Or is there some other function I need to call?
The fix for this was changing from using a namespace to reference the CustomControl to using a src with a filename
changing this:
<%# Register Assembly="MyProduct" Namespace="MyProduct.CustomControls" TagPrefix="cc" %>
to this:
<%# Register src="/CustomControls/MyControl.ascx" tagname="MyControl" tagprefix="uc2" %>

Resources