Structs and Classes not allowed in single page ASP.NET - 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.

Related

Webforms: how to specify different content for a given masterpage

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
}

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

How do I stop <%= from html encoding my script tags?

I am trying to add js dynamically to my view using a custom HTML Helper. The problem I am facing is that the the following server tag is encoding my < and > to &lt and &gt.
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
<%: Model.ProductName %>
<%foreach (var script in Model.DynamicIncludes)
{%>
<%=Html.ScriptTag(Url.Content(script))%>
<%} %>
</asp:Content>
This is what my helper looks like:
public static class ScriptHelper
{
public static string ScriptTag(this HtmlHelper helper, string path)
{
return string.Format("<script src='{0}' type='text/javascript'/>", path);
}
}
When I view the html source the script includes are being written to the reponse stream like so:
<script src='../../Scripts/DataOutEventHandling.js' type='text/javascript'/>
This application is written using the ASP.NET MVC 2.0
Use Html.Raw around your formatted value. You can place this anywhere you find approprate. e.g.
<%=Html.Raw(Html.ScriptTag(Url.Content(script)))%>
http://msdn.microsoft.com/en-us/library/system.web.webpages.html.htmlhelper.raw(v=vs.99).aspx
<%=Html.ScriptTag(Url.Content(script))%> will not encode. You probably use <%:Html.ScriptTag(Url.Content(script))%> which performs the HTML encoding.
Notice the difference between <%= and <%:.
For some reason the script tags were being nested. In my helper I added a closing tag rather than using a self closing script tag and it fixed the problem.
public static string ScriptTag(this HtmlHelper helper, string path)
{
return string.Format("<script src='{0}' type='text/javascript'></script>", path);
}

Best Practices - set jQuery property from Code-Behind

I need to set a single property in a jQuery command using a value that is calculated in the code-behind. My initial thought was to just use <%= %> to access it like this:
.aspx
<script type="text/javascript" language="javascript">
$('.sparklines').sparkline('html', {
fillColor: 'transparent',
normalRangeMin: '0',
normalRangeMax: <%= NormalRangeMax() %>
});
</script>
.aspx.cs
protected string NormalRangeMax() {
// Calculate the value.
}
It smells odd to have to call from the ASPX page to just get a single value though. Not to mention I have an entire method that does a small calculation just to populate a single property.
One alternative would be to create the entire <script> block in the code-behind using clientScriptManager.RegisterClientScriptBlock. But I really don't like putting entire chunks of JavaScript in the code-behind since its, well, JavaScript.
Maybe if I end up having many of these methods I can just put then in a partial class so at least they are physically separate from the rest of the code.
What method would you recommend as being easy to understand and easy to maintain?
The <% %> works fine. One thing that I do is set a value in a hidden field on the page (then writing the necessary javascript to extract that value), this is nice because I can change that hidden field via javascript and when/if the page posts back I can get that new value from code behind as well.
If you need to call the method on demand, you could do an jQuery AJAX call to a ASP.NET WebMethod to grab the data and re-populate the various options. You can find a good tutorial on how to do that here: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Below is some sample code using the hidden field method (using the datepicker control, but you'll get the idea):
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtCalendar" runat="server" />
<asp:HiddenField ID="hfTest" runat="server" />
</div>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://ui.jquery.com/latest/ui/ui.datepicker.js"></script>
<script type="text/javascript">
var dateMinimum = new Date($("#<%= hfTest.ClientID %>").val());
$(function() {
$("#<%= txtCalendar.ClientID %>")
.datepicker({
minDate: dateMinimum
});
});
</script>
</body>
And the code behind Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
// Set Value of Hidden Field to the first day of the current month.
this.hfTest.Value = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).ToString("MM/dd/yyyy");
}
Personally, I would use the <% %> method. This is what the view is for. I don't like the RegisterClientScriptBlock at all. If you ever move to MVC you will get used to the <% %> ... :)
I ran into this problem a while back. I recommend <% %> for single variable stuff. I find the RegisterClientScriptBlock function useful only if I ever need the code-behind to determine which scripts to run.
Rick has a nice article about passing server vars to client script

Resources