How to dynamically add rows to a table in ASP.NET? - c#

So today I started learning ASP.NET. Unfortunately I haven't found any good tutorials online, and I can't afford to buy books at the moment, so I've had to create a ASP.NET web application in Visual Studio 2010 and just play around with the default project setup.
So far here's what I have in my Default.aspx:
<%# 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>Project Management</title>
</head>
<body>
<div style="padding-bottom:10px;"> Project Management System</div>
<div> <table style="width:100%;">
<tr>
<td>Name</td>
<td>Task</td>
<td>Hours</td>
</tr>
</table></div>
</body>
</html>
I created a simple table with the header row already in there. Through a C# script, I want to be able to dynamically add rows to this HTML table. Is this the right way of thinking in ASP.NET? If so, how can I do this? I'm sure I'll need an "Add" button, which adds a new row to the table, with editable fields, and a "submit" button which adds some stuff to a database.
Basically just a rundown of how this is done would be ever so helpful.

Have you attempted the Asp:Table?
<asp:Table ID="myTable" runat="server" Width="100%">
<asp:TableRow>
<asp:TableCell>Name</asp:TableCell>
<asp:TableCell>Task</asp:TableCell>
<asp:TableCell>Hours</asp:TableCell>
</asp:TableRow>
</asp:Table>
You can then add rows as you need to in the script by creating them and adding them to myTable.Rows
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
cell1.Text = "blah blah blah";
row.Cells.Add(cell1);
myTable.Rows.Add(row);
Given your question description though, I'd say you'd be better off using a GridView or Repeater as mentioned by #Kirk Woll.
EDIT - Also, if you want to learn without buying books here are a few sites you absolutely need to become familiar with:
Scott Guthrie's Blog
4 Guys from Rolla
MSDN
Code Project Asp.Net

in addition to what Kirk said I want to tell you that just "playing around" won't help you to learn asp.net, and there is a lot of free and very good tutorials .
take a look on the asp.net official site tutorials and on 4GuysFromRolla site

ASP.NET WebForms doesn't work this way. What you have above is just normal HTML, so ASP.NET isn't going to give you any facility to add/remove items. What you'll want to do is use a Repeater control, or possibly a GridView. These controls will be available in the code-behind. For example, the Repeater would expose an "Items" property upon which you can add new items (rows). In the code-front (the .aspx file) you'd provide an ItemTemplate that stubs out what the body rows would look like. There are plenty of tutorials on the web for repeaters, so I suggest you google that to obtain further information.

public partial class result : System.Web.UI.Page
{
static DataTable table1 = new DataTable("Shashank");
static DataSet set = new DataSet("office");
protected void Page_Load(object sender, EventArgs e)
{
lblEmployeeNumber.Text = HttpContext.Current.Request.Form["txtEmployeeNumber"];
lblFirstName.Text = Request.Form["txtFirstName"];
lblLastName.Text = Request.Form["txtLastName"];
lblTitle.Text = Request.Form["txtTitle"];
Int32 Rcount = Convert.ToInt32(table1.Rows.Count);
if (Rcount == 0)
{
table1.Columns.Add("ID");
table1.Columns.Add("FName");
table1.Columns.Add("LName");
table1.Columns.Add("Title");
table1.Rows.Add(lblEmployeeNumber.Text, lblFirstName.Text, lblLastName.Text, lblTitle.Text);
set.Tables.Add(table1);
}
else
{
if (lblEmployeeNumber.Text != "")
{
DataRow dr = table1.NewRow();
dr["ID"] = lblEmployeeNumber.Text;
dr["FName"] = lblFirstName.Text;
dr["LName"] = lblLastName.Text;
dr["Title"] = lblTitle.Text;
table1.Rows.Add(dr);
}
}
gvrEmp.DataSource = set;
gvrEmp.DataBind();
}
}

You need to get familiar with the idea of "Server side" vs. "Client side" code. It's been a long time since I had to start, but you may want to start with some of the video tutorials at http://www.asp.net.
Two things to note: if you're using VS2010 you actually have two different frameworks to chose from for ASP.NET: WebForms and ASP.NET MVC2. WebForms is the old legacy way, MVC2 is being positioned by MS as an alternative not a replacement for WebForms, but we'll see how the community handles it over the next couple of years. Anyway, be sure to pay attention to which one a given tutorial is talking about.

You can use the asp:Table in your web form and build it via code:
http://msdn.microsoft.com/en-us/library/7bewx260.aspx
Also, check out asp.net for tutorials and such.

Dynamically Created for a Row in a Table
See below the Link
http://msdn.microsoft.com/en-us/library/7bewx260(v=vs.100).aspx

Link for adding through JS
https://www.youtube.com/watch?v=idyyQ23joy0
Please see the below link as well. This would help you add the rows dynamically on the fly:
https://www.lynda.com/C-tutorials/Adding-data-HTML-tables-runtime/161815/366843-4.html

<html>
<head>
<title>Row Click</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function test(){
alert('test');
}
$(document).ready(function(){
var row='<tr onclick="test()"><td >Value 4</td><td>Value 5</td><td>Value 6</td></tr>';
$("#myTable").append(row);
});
</script>
</head>
<table id="myTable" >
<th>Column 1</th><th>Column 2</th><th>Column 3</th>
<tr onclick="test()">
<td >Value 1</td>
<td>Value 2</td>
<td>Value 3</td>
</tr>
</table>
</html>

You need to use JavaScript in your HTML and make sure you are using forms so that. You may finally serialize the data using Ajax method to push the data from HTML into database

Related

Retrieving html data from database to create a page

I have stored html file in database. Now I would like to get data using cs file and link it to my view page. Below is my example of how I have save my able.
My database table contains two columns (page_header, page_footer).
page_header
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
page_footer
<footer>
<table width="100%">
<tr>
<td>
Written by Jon Doe.<br>
Visit us at:<br>
Example.com<br>
Box 564, Disneyland<br>
USA
</td>
<td>
Visit our Site
</td>
</footer>
I want to retrieve those data to my aspx page. Can anyone help in doing that. Or if any demo is available which will be helpful understand how to do that.
If this post is not related please don't degrade. Just let me know, I will delete it.
This is how you get user-specific information to your user without having to hand-update every single page you ever serve:
<!DOCTYPE html>
<html>
<head>
<title runat="server">Page Title</title>
</head>
<body runat="server">
<div id="welcomeDiv" runat="server"></div>
<div id="dataDiv" runat="server">
<datagridview id = "customerData" runat="server">
</div>
</body>
</html>
then, in your codebehind file:
private void Form1_Load(object sender, EventArgs e)
{
//load name from db
Form1.Title = "Welcome back, Mr. "+customer.LastName;
welcomeDIV.InnerHtml = "<b>It's been "+customer.daysSinceLastVisit.ToString()+" days since you last visited! How are "+customer.wifeName+" and the boys?</b>";
customerData = loadDataGrid(customer.ID);
}
It seems that you are creating some kind of a multi-tenant system and need a small amount of customization for each tenant.
There is no reason not to store HTML templates in a database—CMSes such as Wordpress do that a lot. However, to #ShannonHolsinger's point, you should ensure that your database schema is normalized to a reasonable extent. Consider storing e-mail address, contact name, address and website URL as separate fields.
For a templating system, there are many types of choices. You should explore some so you can choose one that is most familiar to you or your needs. In every case, though, be sure that data is property escaped to HTML or you could be allowing your page to be taken over. If you just paste strings together, such as by using InnerHtml then someone could enter their name as </div><script>ChangeTheEntirePageToWhatEverILike()</script> or </div><script>InjectInSomeCodeToSendFormDataToMySite()</script> and it would be seen by the browser as your code rather than as text.
One templating technique could involve client-side data binding. Some popular libraries are Knockout and Angular 2. For client-side data binding, you could put variable references in trusted header and footer HTML and then pass the variable values to be bound as JavaScript data. In other words, let the browser do any data merging that's needed rather than ASP.NET.

C# having control over HTML elements

jQuery and JavaScript can manipulate DOM like anything. But if C# has to send something to the client, then in my knowledge, we can only user Response object to write something in the browser. Now, this would write text in the browser, but we do not have control over where would it write it. Is there anyway that we can control from C#, somehting like :
"This is the text and I want it to be innerHTML of some particular DIV"?
You have two ways to go about doing something like this.
Make your div runat="server" and then it's accessible from the back end to manipulate
Register a JavaScript call using ClientScriptManager.RegisterClientScriptBlock and manipulate the div that way.
But also as Chuck has mentioned in his comment - that's a rather odd thing to do in ASP.NET. For the most part you'd use Label, Literal etc. server controls to add and manipulate text on a page instead of modifying native DOM elements directly.
That's not really how the internet works. When your browser navigates to a webpage, it sends a request to a server. The server responds with something. If it's trying to show a whole webpage, it needs the HTML of the whole page back. C# is powering the webserver.
When you browse to another page, you're not modifying an existing page; you're getting a whole new page back. We use JavaScript to get around that by letting it put out calls to webservers and use the information it gets back to modify the HTML on page, which it does know about, because it's running client-side.
So: no.
You can set the inner html of a div from your code behind. Just ad a runat="server" attribute to the div
<div id="divUserInfo" runat="server"></div>
and in your code behind
string strHtml="<h3> User Name </h3><p>User description</p>";
divUserInfo.innerHtml=strHtml;
This is in VB.NET, but I am sure C# has an equivalent. Just inject some javascript to do what you want.
ClientScript.RegisterStartupScript(Me.GetType, "myScript",
String.Format("<script>document.getElementById('{0}').innerHTML = '{1}';</script>", elementID, html))
.NET provides frameworks to do this - check out WebForms or MVC
From this article on MSDN:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Message.InnerHtml = Server.HtmlEncode("Welcome! You accessed this page at: " + DateTime.Now);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>HtmlContainerControl Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<span id="Message" runat="server"></span>
</div>
</form>
</body>
</html>

TextBox AutoPostBack pre-empts further events

In a simple ASP page, TextBox AutoPostBack events will prevent Button click events (except where button is tapped very quickly) and AutoPostBack events for other controls (like ListBox).
There's a similar question here, but I wasn't happy with being forced to use client side or AJAX solutions: Have to click button twice in asp.net (after autopostback textbox)
Example ASPX page:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="temp.aspx.cs" Inherits="temp" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="PostBack"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="PostBack" Text="Button" /><br />
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="PostBack">
<asp:ListItem>value1</asp:ListItem>
<asp:ListItem>value2</asp:ListItem>
</asp:ListBox><br />
<br />
Events Fired:<br />
<asp:TextBox ID="TextBox2" runat="server" Height="159px" TextMode="MultiLine" Width="338px"></asp:TextBox></div>
</form>
</body>
</html>
C# code behind:
public partial class temp : System.Web.UI.Page
{
protected void PostBack(object sender, System.EventArgs e)
{
this.TextBox2.Text += string.Format("PostBack for - {0}\n", ((System.Web.UI.Control)sender).ID);
}
}
I've been able to partially solve this problem for buttons by using mousedown instead of click events to submit the form (I also blocked extra AutoPostBack events client-side and handled any extra field changes during button click events server side)
However, this means my buttons aren't quite behaving in the standard (click on release) way.
Is there a better solution to this problem that doesn't require trying to do everything in javascript client-side? (I'm writing a lot of code that reads server data during these postbacks, so javascript isn't an ideal solution.)
I'm also trying to avoid switching to an AJAX library for these pages since every new library I add has to go through security auditing etc.
Note: I'm currently working with ASP.Net 2.0/VS 2005, but if this type of problem is fixed in a later release that would be a compelling argument to upgrade. (As far as I understand it, the same problem seems to happen in ASP.Net 4/VS 2010)
The reason to set AutoPostBack="true" on a field (or other input control) is because you want the page to postback when that control's data changes - without requiring that the user click a button. It sounds like that is exactly what is happening: when the field loses focus, the page does a postback.
Perhaps I'm misunderstanding the question? Can you provide some more information about how you need the page/form to behave?
Edit: more info, based on comment from OP.
I think I understand: the "normal" case is they select something from a DropDownList1, and you autopostback to set the values of DropDownList2, based on the selected item in DropDownList1. However, the user may not care about the second list; if they click "search", you want the button-click to essentially abort the autopostback (already in progress), and initiate a new postback.
Unfortunately, I don't think there's any functionality in any version of ASP.NET to "abort" a postback already in progress (not from the client-side code, anyway). Therefore, in order to implement the above behavior, you're going to have to do something outside the standard ASP.NET postback behavior. Here's a few ideas, though by no means is it an exhaustive list:
Use AJAX and JS to retrieve the contents of DropDownList2. If the user clicks search while that ajax call is in progress, the page should postback right away.
Store all possible DropDownList2 data in JSON format in your page; use purely client-side JS to populate List2 when List1 changes. Again, if the user clicks "search", the page will postback right away. Depending on how big the pool of possible List2 entries is, this may bloat the page size too much to be workable.
Use client-side JS to disable your search button when List1 changes selection. The user won't be able to click "search" until the autopostback (to fill List2) completes.
Hope this helps!
To make the client side be more interactive and reduce sending all that viewstate and redrawing the page, I add a little jquery into the mix. It makes things like what you are proposing possible. jquery even ships with the asp.net MVC framework so there is no shame in using it with asp.net.
Here is a simple example that uses jquery that demonstrates what I think you want.
First, in the aspx file, add in a reference to the jquery library. I use the
Google content delivery network so you don't even have add this file to your VS project.
Then take the auto postback references out of all your server controls except the button. I left that one to continue doing a postback because I suspect at some point you want a regular post back, all the other controls use ajax to get your server side response.
I started by using your example page with these modifications:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="temp.aspx.cs" Inherits="temp" %>
<!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>Untitled Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
// Establish where the output goes.
var outputObject = $("#<%=TextBox2.ClientID %>");
// create a function to do an ajax postback
function doAjaxPostback(sender, value) {
$.ajax({
type: "POST",
url: "temp2.aspx",
data: "id=" + sender.attr("id") + "&value=" + value,
success: function (data) { outputObject.append("<br />" + data) }
});
}
// Use jquery to wire up the event handler. We use the ClientID property in case these
// elements get embeded in some other server control container later.
$("#<%=TextBox1.ClientID %>").keyup(function (event) { doAjaxPostback($(this), $(this).val()); });
$("#<%=TextBox1.ClientID %>").change(function (event) { doAjaxPostback($(this), $(this).val()); });
$("#<%=ListBox1.ClientID %>").change(function (event) { doAjaxPostback($(this), $(this).val()); });
// Use a plain html button tag for ajax only. The server control button gets rendered as
// a submit button which requires it to be handled a little differently.
$("#PlainButton").click(function (event) { doAjaxPostback($(this), $(this).attr("value")); event.preventDefault(); });
});
</script>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="PostBack" Text="Button" /><br />
<button id="PlainButton" value="Plain Old Button">Ajax Only, No postback</button>
<br />
<asp:ListBox ID="ListBox1" runat="server" >
<asp:ListItem>value1</asp:ListItem>
<asp:ListItem>value2</asp:ListItem>
</asp:ListBox>
<br />
<br />
Events Fired:<br />
<asp:TextBox ID="TextBox2" runat="server" Height="159px" TextMode="MultiLine" Width="438px"></asp:TextBox>
</div>
</form>
</body>
</html>
Then for the code behind I just made a tiny change so we can report when we get a regular postback versus the ajax kind:
protected void PostBack(object sender, System.EventArgs e)
{
this.TextBox2.Text += "\n\nGot an asp.net postback\n\n"
+ string.Format("PostBack for - {0}\n", ((System.Web.UI.Control)sender).ID);
}
Okay, so I was trying not to get too fancy but I wanted to demonstrate how easy this is so I made a second page, temp2.aspx but left the aspx file alone as i only needed what is in the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class temp2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = string.Empty;
string value = string.Empty;
Response.Clear();
if (Request.Form == null || Request.Form.Count < 1)
{
Response.Write("I got nothin'");
Response.Flush();
Response.End();
return;
}
id = Request.Form["id"];
value = Request.Form["value"];
Response.Write(string.Format("\nevent from: {0}; value={1}",id,value));
Response.Flush();
Response.End();
}
}
}
Notice that what I did was clear, write, flush and end the response so only the text we want is sent back to the caller. We could have done some fancy stuff in the page_load of the original temp page to check if it is a call from the ajax function that will not clear or flush the response if the incoming Request.Form does not contain a certain field, etc. But by doing it as a separate page, I hoped to simplify the code. This also opens up possibilities.
Say you have a country drop down that has Canada and USA in it and when it changes, you want to sent back data to populate a State/Province dropdown with the appropriate values. By putting the lookup code on its own page the way I did with temp2.aspx, you can then call it from all the pages in your app that have a need for such a service.
Good luck, let me know if you have any trouble understanding my code.

ASP.net Page Loading popup

I was wondering if it is possible to have a modalpopup show up on page load, saying that the page is loading. I have a page that gets a lot of data from an external source which means it takes a bit before any of the controls are actually filled.
I would like to have a popup or something similar that tells the user the page is loading.
I tried this:
<ajax:ModalPopupExtender ID="mpeLoader" runat="server" TargetControlID="btnLoader"
PopupControlID="pnlLoading" BackgroundCssClass="modalBackground" />
<asp:Panel ID="pnlLoading" runat="server" Width="100px" Style="display: none;">
<div class="detailspopup">
<table>
<tr>
<td><asp:Image ID="imgLoader" runat="server" ImageUrl="~/App_Themes/Main/img/loading.gif" /></td>
</tr>
<tr>
<td>Loading...</td>
</tr>
</table>
</div>
</asp:Panel>
with a dummy button btnLoader to allow me to access the show and hide from code behind. I've been toying with the .show method in the page lifecycle but I can't seem to find a way to have the poopup show when the page is loading (and disappear when loading is done). This would also be needed upon filtering the data, thus getting new data based on filter data.
Hard to say what the best solution is without more information, but one possible way to go is to make the first page just act as a "loader" containing the dialog and some javascript that will load the actual page with ajax.
Like I wrote before it depends very much on what you are trying to accomplish :-) !
But one way to do it with jQuery, if the page you are trying to load is very simple like a list without any state / postback controls is to create a "Loader"-page like the code belov and use the UrlToLoad query param for what page to load dynamically.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function()
{
$("form").load("<%= this.Request["UrlToLoad"] %> form");
});
</script>
</head>
<body>
<form runat="server">
Loading...
</form>
</body>
Have you considered using jQuery? There are some excellent modal dialog plugins available. I've used Eric Martin's SimpleModal extensively in the past, and have been very happy with it. It has hooks for callbacks both before and after displaying the dialog, so you could perform any checks you need to using functions.
Using the jQuery route - you could have a div that surrounds all the content that is still loading, and have is dimmed out/disabled with a modal dialog showing your 'page loading' message. Then you could make use of the $document.ready() functionality in jQuery to determine when the page is done loading. At this point, you could remove the dialog and fade the page in.
What I did is make a PreLoader.aspx page that will "hold" untill the page we want is loaded:
<script type="text/javascript" language="javascript">
window.onload=function()
{
$get("ctl00_ContentPlaceHolder1_btnNav",document).click();
setTimeout('document.images["Loader"].src="App_Themes/Main/img/loading.gif"', 200);
}
</script>
the button actually makes the transfer
<asp:Label ID="lblLoading" runat="server" Text="Loading the requested page. Please wait ..." />
<asp:Button ID="btnNav" Style="display: none;" runat="server" OnClick="NavTo" />
protected void NavTo(object sender, EventArgs e)
{
Response.Redirect(Request.QueryString["url"].ToString());
}
I like this as it can be reused for every heavy data page ...

Adding meta tag programmatically in C#

I'm trying to programmatically add a <meta>. It is working fine when there is a Head element with runat = "server" in the .aspx page.
The code behind is:
HtmlMeta meta = new HtmlMeta();
meta.Name = "robots";
meta.Content = "noindex,follow";
this.Page.Header.Controls.Add(meta);
But I have some script in the head tag which contains code blocks like <% ... %>, so I cannot keep the runat = "server" value.
The problem is I have to add the meta tag programmatically, because it depends on a value from the database.
Is there a way to solve this issue so that my script inside the head element works as usual and I can add a meta tag programmatically?
OK, I tested the answer by veggerby, and it works perfectly:
In the <header> section:
<asp:PlaceHolder id="MetaPlaceHolder" runat="server" />
Note that Visual Studio might show a warning on the PlaceHolder tag, because it is not recognised as a known element inside the header, but you can ignore this. It works.
In the C# code:
HtmlMeta meta = new HtmlMeta();
meta.Name = "robots";
meta.Content = "noindex,follow";
MetaPlaceHolder.Controls.Add(meta);
Alternatively (since you already have code blocks using <% %> in your header section), you can tag the meta directly and retrieve only the value from server side:
<meta name="robots" content="<%=GetMetaRobotsValueFromDatabase()%>" />
Many thanks to Awe for the solution! I have implemented this code in a (error404.ascx) ASP.NET User Control as follows:
<%# Control Language="C#"%>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.TrySkipIisCustomErrors = true; //Suppress IIS7 custom errors
Response.StatusCode = 404;
SetRobotsHeaderMetadata();
}
private void SetRobotsHeaderMetadata()
{
HtmlMeta meta = new HtmlMeta();
meta.Name = "robots";
meta.Content = "noindex,follow";
this.Page.Master.FindControl("cphPageMetaData").Controls.Add(meta);
}
</script>
With the following masterpage:
<%# Master Language="C#" AutoEventWireup="true" Inherits="MyMaster" %>
<script runat="server">
...
</script>
<!DOCTYPE html>
<html lang="en-GB">
<head>
<title>Site title here</title>
<asp:contentplaceholder runat="server" id="cphPageMetaData">
</asp:contentplaceholder>
</head>
<body>
...
</body>
</html>
Or you could just put your meta-tag in the header, with an ID and a runat="server"... then in the code behind say
myMetaTag.Content = "noindex,follow";
or
myMetaTag.Visible = false;
or whatever you'd like.
I think this is the best approach:
this.Page.Header.Controls.Add(new LiteralControl(#"<meta ... />"));
Enjoy!
Try moving whatever it is that you are doing in the <% .... %> to the code-behind. If you are using the script to add content into the page, you can replace it with an asp:Literal control and then set the value you were previously calculating in the script block to the code-behind and set Literal.Text to that value.
I haven't tested it, but maybe you can add an <asp:Placeholder> inside the <head></head> tag and add the meta tags to this.
The best solution for this, which I successfully checked without any error or warning:
The JavaScript code, which contains the <% ... %> code, was removed from the head section and placed in the body section.
You could define your meta tag as a static string like so:
Private Shared MetaLanguage As String =
String.Format("<meta http-equiv=""Content-Language"" content=""{0}""/>", CultureInfo.CurrentUICulture.TwoLetterISOLanguageName)
Then place them in your head like so:
<head runat="server">
<%=MetaLanguage%>
</head>
This allow you to use any meta tag values and is easy to read and customize. Note: The use of the Shared keyword (static) helps improve performance.
MetaDescription = "Your meta description goes here";
MetaKeywords = "Keyword1,Keyword2,Keyword3";
OK... I actually only use C#... Or HTML into C#. I never use codebehind, designer or webcontrols in the file aspx... So I program everything from classes... And dynamically.
Result:
HtmlMeta meta = new HtmlMeta();
meta.Name = "robots";
`meta.Content = "Here is what you want";`
var page=HttpContext.Current.Handler as Page;
page.Header.Controls.Add(meta);

Categories

Resources