Response.write to <head> - asp.net

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.

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
}

Defining where usercontrol output will be

I am new to ASP.NET and user controls. I am trying to generate a javascript array from my C# code.
On the main .aspx page I have this:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="main.aspx.cs" Inherits="main" %>
<%# Register Src="~/table.ascx" TagPrefix="uc1" TagName="myTable" %>
Then on my table.asc.cs I have this:
protected void Page_Load(object sender, EventArgs e)
{
(...)
this.LoadDataFromDB();
(...)
}
private void LoadDataFromDB()
{
(...)
Response.Write(array);
(...)
}
My problem is that the array is being written before the <html> tags. It still works fine, but, how could I put it inside the <head> tags for instance?
Thank you
UPDATE:
I added this to my main.aspx
<asp:Literal ID="Literalarray" runat="server" Mode="PassThrough" Text="" />
and this to my ascx.cs:
Literal Literalarray= new Literal();
Literalarray.Text = output;
What am I missing?
Use a Literal control instead of Response.Write. Place it on your control somewhere and set its Text property.
You have to place it on your control, not on your page and you don't need to reinitalize it.
This code in the ascx.cs:
Literal Literalarray= new Literal();
Literalarray.Text = output;
should be:
Literalarray.Text = output;
Which should be in the Page_Load as a designer file will declare the literal type and allocate the space for it. By declaring a new one, the old one may be hidden. Also, be aware that if you are generating a JavaScript array that you also generate the script tags as part of the output as a literal doesn't do much decorating around the result.
I'd probably suggest putting a literal in the head on the main.aspx and load the data in there that way for one idea.
You could also do dynamic controls so that in the table.ascx.cs you create a Literal like you did previously and then add that to the head of the page assuming the head tag has a "runat=server" attribute so the code behind can use it. I'm pretty sure that in the code behind for the table you could do something like this:
Literal Literalarray= new Literal();
Literalarray.Text = output;
this.Page.head.AddControl(Literalarray);

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);
}

ASP.NET Line Breaks in Title Element

I'm trying to optimize SEO readability on our websites and one issue I've come across is ASP.NET butchering the title element of my MasterPage. Entered as such in my MasterPage (manually reformatted to remove line breaks caused by the <% %> tags):
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /> - <%=WebsiteSettings.WebsiteName %></title>
This is the output I receive:
<title>
Home
- Website Name</title>
As you can see ASP.NET is adding preceding and trailing line breaks where the <asp:ContentPlaceHolder /> is substitute becaused Visual Studio auto-formats <asp:Content /> to start and end with a line break. Obviously, this can be prevented in the Visual Studio formatting options, but this is not ideal because I only would want to remove that behavior for the TitleContent placeholder and not the rest.
Is there any way I can ensure my Title is trimmed before it is rendered? I am using MVC so code-behind is not an acceptable option.
The following should allow you to keep from copying and pasting code.
Option 1
Since your using MVC create a HTML Helper Like this:
namespace [ProjectName].Web.Views
{
public static class HtmlHelpers
{
public static MvcHtmlString GetFullPageTitle(this HtmlHelper helper, string PageTitle)
{
return MvcHtmlString.Create(PageTitle + " - " + WebsiteSettings.WebsiteName)
}
}
}
Now in your Master Page just put this
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
Then in your pages use this
<asp:Content ID="PageTitleContent" ContentPlaceHolderID="TitleConent" runat="server">
<%=Html.GetFullPageTitle("Some PageTitle")%>
</asp:Content>
Option 2
Note: if you populate Data in your Action then you dont have to Add this to ever page.
Like so:
public ActionResult myAction()
{
ViewData["Title"] = "MyActionTitle";
return View()
}
Then in your Master page you would simply do the following
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /><%= ViewData["Title"] + "-" + WebsiteSettings.WebsiteName %></asp:ContentPlaceHolder></title>
The nice thing about this is if you wanted to you could override what the title says in each page by doing this
<asp:Content ID="PageTitleContent" ContentPlaceHolderID="TitleConent" runat="server">
My Override Title
</asp:Content>
If you are really bothered (and I don't see why you would be given whitespace is not important in HTML) you could try setting it in code-behind something like this:
Page.Title = WebsiteSettings.WebsiteName + " " + Page.Title;
Using regular expressions, as dagray said, is the safest and easiest approach.
This code replaces only the first occurrence of newline/characters in first title tag.
void TrimTitleRegex(ref string content)
{
System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(#"\<title\>(.*?)\<\/title\>");
var result = rgx.Replace(content,
m =>
{
var codeString = m.Groups[1].Value;
// then you have to evaluate this string
codeString = System.Text.RegularExpressions.Regex.Replace(codeString, #"\r\n?|\n", "");
codeString = String.Format("<title>{0}</title>", codeString);
return codeString.Trim();
}, 1);
content = result;
}
You could try a literal control, though I suspect that won't work in the document header outside the asp.net form. You could also try setting the title via code-behind.
This is a possibility -
Override the rendering routine to remove whitespace with regexp's:
http://madskristensen.net/post/Remove-whitespace-from-your-pages.aspx

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