I have a webpage with server accessible controls, see 'FileIconLink' below:
<body>
<p class="FirstTitle style5">Downloads:</p>
<div id="BreadcrumbDiv">
<p style="padding-left:5px; ">Page Loading...</p>
</div><!--/BreadcrumbDiv-->
<div id="DirLinksDiv">
<p><span class="SecondTitle">Files:</span></p>
<a runat="server" href="#" id="FileIconLink">File</a>
<% WriteFileLinks(); %>
<p><span class="SecondTitle">Folders:</span></p>
<a runat="server" href="#" id="FolderIconLink">Folder</a>
</div><!--/DirLinksDiv-->
</body>
<%RemoveHTMLTemplates(); %>
Both 'FileIconLink' and 'FolderIconLink' are templates of web controls which are copied by my code - such as <% WriteFileLinks(); %> above. How could these templates be permanently removed from the web page at run-time on the server without causing the error:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Thanks in advance!
This is because you have <% %> inside the control you're trying to change. Instead of using <% %> in the aspx page, I would modify the code behind to add a literal control or something to the div, like:
DirLinks.Controls.Add(new LiteralControl(WriteFile()));
You should then be able to modify your control form the code behind.
Your inline code is executed during render.
But you probably want to get rid of the templates during Load.
Which means that the two techniques conflict.
Ultimately I realised my approach was wrong, as Cade Roux was alluding to, I needed to make up my mind where the templates were going to be used.
My solution was as follows:
Make controls for containing the results of my (previously inline) code.
Use templates in Page_Load to fill the controls described above.
Delete templates in Page_Load.
Do nothing inline.
The Page object has another function apart from Page_Load function called Page_PreRender, this function gets executed before Page_Load. So please try remove logic in this Page_PreRender function.
Please refer this link http://msdn.microsoft.com/en-us/library/system.web.ui.control.prerender.aspx
Related
The situation is I want to add new button in my html aspx file (existing file). But I keep getting Server Error in '/' Application (Runtime Error) in the page after adding new button. Below is the error:
enter image description here
If I remove back the html markup, the page come back OK.
enter image description here
<asp:button id="btnSelect" runat="server" onclick="select_Click" text="Select"/>
Then, I add inside html markup page , for example below, the Select Button will show a popup message for Selected Date, it's ok like I want. But I cannot add query to save the selected date into SQl database here because the select_Click button event is inside html markup aspx page. It's look like this button is inside Content Control and I'm not allowed to add button inside the existing file of html markup aspx. Then, when I add select_Click event function in my Example.aspx.cs page the button will do nothing. Supposedly the select_Click event function is inside Example.aspx.cs file.
Anyone got any ideas why this happen???
Note: The existing file is created by previous developer.
<script runat="server">
protected void submit_Click(object sender, EventArgs e)
{
string targetdate = Request.Form[TargetDate.UniqueID];
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Selected Date: " + targetdate + "');", true);
}
</script>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="container">
<table id="table2" style="text-align: center; width: 100%">
<tr>
<td class="auto-style1" style="text-align: center; height: 51px;">
<asp:Label ID="lblTitle" runat="server" Text="Case Detail" Font-Bold="True" Font-Size="XX-Large" Font-Names="Verdana" Font-Underline="True"></asp:Label></td>
</tr>
</table>
</div>
</asp:Content>
Thankyou for your time by reading this.
Well, first there is "zero" advantage to put the code inside of a script tags with runat=server.
You will get 100% the SAME effect if you just move that code behind.
(and I suggest you do).
However, looking close at your page, we see it is a "child" page. (in other words, you have a master page in effect here).
Remember, ALL THAT using script with runat=server does is inject the code in CODE behind.
but, that means of course you have to place that good old plain jane code stub inside of the content part since that is ALSO where the current page is being injected/placed.
So, really, I would suggest that you DUMP this idea, and there is no advantage I can think of. Why put code in the markup when you WILL AND ALREADY have a code behind page?
Now, all you doing is creating two places to look at code, and worse yet, when you use ?
All it does is move the code to code behind location anyway!!!
So, your example has to be this:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script runat="server">
protected void submit_Click(object sender, EventArgs e)
{
string targetdate = Request.Form[TargetDate.UniqueID];
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Selected Date: " + targetdate + "');", true);
}
</script>
<div class="container">
<table id="table2" style="text-align: center; width: 100%">
<tr>
<td class="auto-style1" style="text-align: center; height: 51px;">
<asp:Label ID="lblTitle" runat="server" Text="Case Detail" Font-Bold="True" Font-Size="XX-Large" Font-Names="Verdana" Font-Underline="True"></asp:Label></td>
</tr>
</table>
</div>
</asp:Content>
In other words, you have to place that code inside of the "content", since that is where all your markup and "code" has to be placed, and that REALLY amounts to just placing that "stuff" into the "form" tag area on a regular (non master/child page).
However, as I pointed out, really?
Just take that code, cut it out, right click, view->code, and then just paste that code into the code behind. (remove the script tags).
The result will be 100% the same operation.
So, just keep in mind that using "script" with runat="server"?
All it really does is just move that code to the code behind module, and you not find nor see any difference (then if you just had placed that code in the code behind module anyway!).
However, as noted, since you have a master/child page?
Then both markup, and any code for that "child" page?
it has to be placed inside of the content template.
I should also point out in your sample markup? I don't see a button that would run that code stub anyway - so that's missing and that makes even less sense.
So assuming you did add a button inside of that content template?
Then it most certainly could have a click event that runs that button click code stub you have.
So keep in mind the rules that apply to JavaScript code?
They do NOT apply to code behind, and thus the placement rules for script vs script=runat=server does NOT apply in ANY way at all here.
Script tags with runat=server means:
Please move that server side into the code behind code module for that given page. The code running will be 100% the same as if you had placed that server side code directly into the code behind module in the first place. (again: 100% the same result).
So, yes, you should be able to place a button inside of the content template.
like this:
I'm trying to declare a string variable right after the body tag from the approach below and display the value for the name variable inside a div tag. But why can't we access the variables outside the declared scripting tag<%CODE%>?
In other words, if I declare a variable name somewhere in the HTML code
as <% string name="Stark"; %> and try to access it somewhere down in the code using the code below <div><%=name;%></div>...
Then it prompts me with
The <VARIABLE NAME> doesn't exist in current context
ASP.NET MVC
#{
string name = "Stark";
}
<div>
<h2>#name</h2>
</div>
ASP.NET WebForms
<% string name = "Stark"; %>
<div>
<h2><%=name %></h2>
</div>
<%= %> syntax prints an expression.
It doesn't take a full statement (name; makes no sense as a statement, and it doesn't make sense to print a statement).
Therefore, it must not have a semicolon.
I know this is a bit old of a topic but I want to answer it for anyone that stumbles upon this question:
For Webforms, ASP.NET separates variable contexts by the tags they are located in. Sometimes you need to set the variable within the same tag as the call (<%= %>) you are working with so that ASP.NET will compile it.
So...
<label> <!-- scope -->
<% %>
<%= %>
<\label>
Instead of...
<% %>
<label> <!-- scope -->
<%= %>
<\label>
The differences comes when you use an if/for/foreach code blocks in Webforms. The scope surrounding the HTML and C# allows for C# to become the focus instead of the HTML.
This is most likely a scoping issue based on how ASP.NET webforms handles variables in HTML.
If someone can confirm if the scoping ability has improved for razor, that would be awesome.
I have some code that essentially looks like this:
<div>
<% if(Something) { %>
<div id="someUniqueMarkup">
This markup should not be output if Something==true.
<units:MyUserControl runat="server"/>
</div>
<% }
else { %>
<units:MyUserControl runat="server" />
<% } %>
</div>
Depending on Something, one of them is hidden, and that is fine. But if I set break points in the user control, I notice it's being loaded twice (once for each of the controls above) and all it's logic is being run twice. I could of course control this with placeholders or multiviews, but the same thing seems to apply - OnLoad/Page_Load etc is run once for each control that is actually on the page.
EDIT:
The reason why im showing/hiding this is because I need to include some markup around the control if Something == true. I could wrap the "unique markup" itself in if-else before and after the control, but that just seems dirty for something that really should be as simple as I've imagined above. The user control itself should be exactly the same in both scenarios, sorry for the confusing property it had.
Is it just me, or is this just a really unintuitive interface? And is it actually possible to not load/execute a user control at all as long as it's on the page?
Since you have two controls on the page it will render them both. The if-check you create, only determines whether it's included in the output. The easiest way to prevent this is to change your code like this:
<div>
<units:MyUserControl runat="server" SomeSetting="<%= Something %>" />
</div>
EDIT: Answer to edit in the original post:
<div>
<% if(Something) { %>
<div id="someUniqueMarkup">
This markup should not be output if Something==true.
<asp:placeholder id="phItemInDiv" runat="server" />
</div>
<% }
else { %>
<asp:placeholder id="phItemOutsideDiv" runat="server" />
<% } %>
</div>
MyUserControl ctrl = (MyUserControl)LoadControl("/pathtousercontrol.ascx")
if (something){
phItemInDiv.Controls.Add(ctrl);
}
else{
phItemOutsideDiv.Controls.Add(ctrl);
}
This way you will only have the user control emitted (and loaded) if Something is true
The best way, in my opinion, is to declare your user control once in the ASPX.
In the code behind, on PageLoad, apply the logic you see fit:
if(something)
MyUserControl.SomeSettings = ...
If there is a problem in the chronology, do the above logic in PreLoad since it will fire before Page Load of the page and all of its related user controls.
EDIT:
You can put two different IDs on the user controls with Enabled = false.
In Page_load, set Enabled to one of them based on the logic you desire.
I searched a way to include a file in a web application (like a menu, so I won't have to edit it on all pages when applying changes), but haven't found something as simple as
<?php include "Menu.html"; ?>
Can you please help?
Have you looked into Master Pages? They would certainly help you add the same layout across several pages.
Or perhaps you want a reusable User Control (that you write yourself)?
We don't use "include page" in asp.net, even though it is possible (with a different syntax of course). Instead, have a look at Master page concept.
MasterPages allow you to maintain a parent/child relationship between a master page which contains content that wraps around any number of child content pages.
Similarly, UserControls allow you to re-use whatever content you want on whatever page you want, whether it's a MasterPage or ContentPage:
<%# Page Language="C#" %>
<%# Register TagPrefix="uc" TagName="Spinner"
Src="~/Controls/Spinner.ascx" %>
<html>
<body>
<form runat="server">
<uc:Spinner id="Spinner1"
runat="server"
MinValue="1"
MaxValue="10" />
</form>
</body>
Methods (C#)
Executable code:
Page include
<!--#include file="a.aspx"-->
Execute independently inside a page
<% Server.Execute("a.aspx"); %>
Non-executable code:
<% Response.WriteFile("a.inc"); %>
I believe this is what you are looking for.
<!--#include file="wisdom.aspx"-->
I use C#.net
<% Response.WriteFile("YourPage.aspx"); %>
and this works real well for me!!
I also use your line,
<!--#include file="wisdom.aspx"-->
when I am in HTML mode.
I recently put some code <% %> code blocks in my Master Page. Note I've read of the "fix" for either moving things out of <head> or using <%# %> but neither of them work well for my application.
Now the weird thing is that I only get this error on one page of mine. All the other pages seem to work fine, so what actually causes this error? There is nothing I can think of that is unique about this page. It uses the script manager as does other working pages and there is just nothing extraordinary about this page. It does have quite a few custom controls on it, so hunting down what is different in this page is more difficult than usual.
So what actually causes the Controls collection cannot be modified because the control contains code blocks exception?
Things can go wrong when some code tries to add controls to the tag containing the <% ... %> or <%= ... %> code block (in this case your <head> tag).
For instance, when you're using themes, the Page class will automatically add <link> tags to the <head> for every CSS file in your theme's directory. But it could also be triggered by setting the Page.Title.
But there are many more ways that can cause modifications to the <head> tag, so without further information (such as a stacktrace) it's hard to give a definitive answer.
I've come up with something I find a lot easier and more straightforward -- while leaving the tag in the header where it belongs.
First, start the code block with <%# instead of <%= :
<head id="head1" runat="server">
<title>My Page</title>
<link href="css/common.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%# ResolveUrl("~/javascript/leesUtils.js") %>"></script>
</head>
This changes the code block from a Response.Write code block to a databinding expression. Since <%# ... %> databinding expressions aren't code blocks, the CLR won't complain. Then in the code for the master page, you'd add the following:
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
}
The DataBind method evaluates all the databinding expression(s) in your header at load time.
If you have a page or control with <% %> and ever dynamically update the control collection (add a control to the page that isn't defined in the .aspx/.ascx) this error will trigger. To get around this I have used an <ASP:Literal/> to inject data instead of <% %>
If you have themes enabled it could cause it to do that.