Using sections in ASP.NET Webforms - asp.net

I am having a bootstrap problem I hope one of you might have a solution to.
I have placed all my JavaScript references in the bottom of my masterpage. This usually works fine, but now I have a ASCX control which needs to add some JavaScript too the footer (initialization of a module). The reason why I can't initialize the module from the master page is because I need some properties from my codebehind file.
In ASP.NET MVC I would have used sections to inject data from a usercontrol to a section in the masterpage, but is this even possible in ASP.NET Webforms 4?

No, that concept of sections in not available in WebForms.
One way to do what you've described is to use the <%= %> syntax and send the values of server properties to the client (HTML output). In your ASCX control you can have the following markup:
<script type="text/javascript">
var clientProperty = <%= MyServerProperty %>;
</script>
ASP.NET WebForms will substitute the value of MyServerProperty above when it renders the page, and then you can access clientProperty as a global variable from the script in the masterpage.
Another approach is to use a Hidden field and set its value on the server. It will be rendered as an <input type="hidden">, whose value you can then get from any script by ID.
A third option is to load the actual client script only from the ASCX control (when it makes sense), rather than put it in the masterpage (when it will be loaded everywhere in the site).

You could add something like this to the bottom of your master page:
<asp:PlaceHolder runat="server" ID="javascriptSection" />
Then in your page's code behind or in a <% %> tag:
var scriptTag = new HtmlGenericControl("script");
scriptTag.Attributes["type"] = "text/javascript";
scriptTag.InnerHtml = #"function () { ... }";
var javascriptSection = this.Page.Master.FindControl("javascriptSection");
if (javascriptSection != null)
javascriptSection.Controls.Add(scriptTag);

Related

ASP.NET Web Site to Web Application conversion error

We had a Visual Studio Website project.
We needed a .VBPROJ so I had to convert our Web Site Project to a Web Application Project.
I followed several walktrough, did everything well for the conversion :
create new webapp project
add references
copy files (from website
to webapp folder)
include them in the project
click "Convert to Web App".
After all that , i get three identical compilation errors, javascript related with an .ASPX page.
<%# Page Language="VB" AutoEventWireup="false" MasterPageFile ="~/GAR.master" Inherits="GARWA._Default" Codebehind="Default.aspx.vb" %>
'TableWeekID' is not declared. It may be inaccessible due to its protection level.
<script type="text/javascript" language="javascript">
//Very important variable!
var TableWeekTag = '<%=TableWeekID%>'
var DivYearSmallTableTag = '<%=DivYearSmallTable%>'
var TableNameTag = '<%=TableNameID%>'
What's the problem here ?
Thanks
You can do it in this way.
Use a Hiddenfield control and store the server variable value in it.
One hidden field for each server variable.
And get the value into the javascript function document.getElementById()
Use the below to POPULATE the serverside input control(s) datavalues first.
ASPX SERVERSIDE CODE
svrTableWeek.Value = TableWeekID
svrDivYear.Value = DivYearSmallTable
svrTableName.Value = TableNameID
Also, if you opt for the SERVERSIDE Inputs then you need the following HTML in your ASP page
USING ASP SERVER CONTROLS FOR HIDDEN VALUES
<asp:HiddenField ID="svrTableWeek" runat="server" />
<asp:HiddenField ID="svrDivYear" runat="server" />
<asp:HiddenField ID="svrTableName" runat="server" />
And if you prefer CLIENTSIDE inputs then use the code below instead of ALL of the above
USING HTML (clientside) CONTROLS FOR HIDDEN VALUES
<input type="hidden" id="svrTableWeek" name="svrTableWeek" value="<%=TableWeekID%>" />
<input type="hidden" id="svrDivYear" name="svrDivYear" value="<%=DivYearSmallTable%>" />
<input type="hidden" id="svrTableName" name="svrTableName" value="<%=TableNameID%>" />
Finally regardless of which of the two above methods you choose,
now your ready to re-use those values in your clientside javascript
CLIENT SIDE SCRIPT ROUTINES
<script type="text/javascript" language="javascript">
//Very important variable!
var sTableWeek = document.getElementById('svrTableWeek').value;
var sDivYear = document.getElementById('svrDivYear').value;
var sTableName = document.getElementById('svrTableName').value;
It seems a bit long winded I know, but it should work without issues.
Try global replacing all of the "~/GAR with "GAR . I just converted a Web Site to a Web App, had similar odd errors, all because the virtual reference to the master page files was no longer correct. My first indicator was a DIV ID that wasn't seen in a code-behind file.

ASP.NET #Register vs. #Reference

I'm working with referencing user controls on my ASPX page and I'm wondering what the difference is between these two page directives.
#Reference
#Register
#Register is primarily used for registering tag prefixes to declaratively use controls within a page.
<%# Register tagprefix="my" namespace="MyNamespace" %>
<my:CustomControl runat=server />
#Reference is primarily used to refer to a page or user control (by file name or virtual path) to programatically refer to members of the page or control.
<%# Reference Control="MyControl.ascx" %>
<% MyControl ctrl = (MyControl) Page.LoadControl("MyControl.ascx");
ctrl.CustomProperty = "..."; //REFERENCE directive is needed to access property
%>
#Register is the more commonly used directive. You use this when you want to use a user control in your aspx or ascx page declaratively. #Register associates the control with a specific prefix and you can then use it in your markup.
#Reference only tells ASP.NET to compile the other control when your aspx or ascx page is compiled. That makes sure it is available at run-time and can be added to your control hierarchy programmatically. This is less common since dynamically changing user controls at runtime is not comon.
Here's a good blog post about it.
http://weblogs.asp.net/johnkatsiotis/archive/2008/08/13/the-reference-directive.aspx

ASP.Net <%# %> and <%= %> rules?

Can someone explain to me the rules around what can and cannot be evaluated/inserted into markup using the <%# %> and <%= %> tags in asp.net?
When I first discovered I could inject code-behind variables into mark-up using <%= I thought 'great'. Then I discovered that if such tags are present you can then not add to the controls collection of the page (that's a whole different question!). But <%# tags are ok.
Is there a way I can inject a code-behind variable or function evaluation into the page using <%# ? Thanks.
<%%> are code blocks. You can put any server side code in them. This is a shortcut for <script runat="server"></script>.
<%=%> is for outputting strings. This is a shortcut for <script runat="server">Response.Write()</script>.
See here for more detail about <%%> and <%=%>.
<%#%> are used for data binding expressions.
See the index page for asp.net Page syntax.
The <%# inline tag is used for data binding, so if you want to use a code-behind variable inside it, you will have to bind the page or control the variable resides in:
Page.DataBind();
You can include this statement in the Page_Load or Page_PreRender event.
See this article for more information about the use of inline tags in ASP.Net, and this article for more about server-side databinding.

How can the literal contents of a PlaceHolder be read?

I have some code on a User Control that looks like this:
<asp:PlaceHolder id="ph1" runat="server">
<script type="text/javascript">
jQuery(function() {
doSomethingAwesome();
});
</script>
</asp:PlaceHolder>
I want to get the contents of the PlaceHolder control. I'm trying to get it in the OnPreRender of the page this control is on. I would have expected that the contents of the PlaceHolder would be be a single Literal control, but the Controls collection is empty.
How can I get the contents of the PlaceHolder control on the server side?
Literal content doesn't exist on the server because it's not in a server control.
If you need to make the script visible on the server, you'll need to explicitly put it inside a server control with the "runat=server" property set.
To get contents on client side you can do
$('#ph1').html()
If using naming containers which is likely because of user controls
$('#<%=ph1.ClientID%>').html()

Form tag on ASP.net page

I have a web application that has a page that loads the content from the database. I want to be able to put a form in the dynamic content, but .net doesn't let the inside form perform it's action. Is there a way to allow this or some other way I can get a form on a dynamic content page?
--EDIT--
I think I need to clarify something. This is an aspx page that loads content from the database. As far as I know, the text I pull from the db and stick in the Label is never compiled or processed by the .net wp, thus I can't use the code behind to fix this issue.
This is a common problem, when you want to have a non-postback form to a 3rd party site (like a PayPal button, for example).
The problem occurs because HTML doesn't let you have form within a form, and most ASP.NET pages have a <form runat="server" /> "high up" in the HTML (or in the Master page).
My favorite solution is to hide the "high up" form tag, while still showing all of the content. Then you can feel free to dump any tags you want in the body. If you do this dynamically you can choose on a page-by-page basis which pages have custom forms.
I created a class called GhostForm.cs to handle this. You can read all about it here:
http://jerschneid.blogspot.com/2007/03/hide-form-tag-but-leave-content.html
There can only be one form on the page (the asp form); you have to use that form somehow.
To clarify, there can only be one form processed.
Not with webforms, no. You have to work within the one, full page form by using an event handler connected to a Button to LinkButton. Fortunately, it's pretty easy to do:
foo.aspx:
...
<asp:TextBox id="txtFoo" runat="server" />
<asp:Button id="btnFoo" runat="server" onclick="btnFoo_Click />
...
foo.aspx.cs:
...
protected void btnFoo_Click(object sender, EventArgs e)
{
string s = txtFoo.Text;
// do something with s
}
...
Dino Esposito has an article from MSDN magazine that covers handling multiple forms or "simulating" sub forms in ASP.Net that might just answer all your questions.
http://msdn.microsoft.com/en-us/magazine/cc164151.aspx
Any work around would be hacky and very ugly. By design asp.net uses a form tag to post and get data. This is why they call it a Web Forms Application. Html does not allow nested forms. What you want to do is use a WebRequest in your code behind.
If you are trying something like a paypal button you could simply use something like this.
Markup:
<div id="PayPalButtonContainer" runat="server"></div>
Code Behind:
public static string GetPayPalButtonMarkup()
{
const string markup = #"https://www.paypal.com/cgi-bin/webscr
?cmd=_xclick&business={0}
&item_name=Widget
&amount={1}
&currency_code=USD";
return markup;
}
PayPalButtonContainer.InnerHtml = string.format(GetPayPalButtonMarkup,"YOUR PAYPAL USER NAME", "YOUR PRICE VALUE");
you either have to deal with the postback by adding a server side click event handler to what you want to be the "sub forms" submit button (this is how web formas deals with multiple submit type buutons on the same page) or do soemthing clever with AJAX if you dont want a full post back
I've run across this issue before. One workaround that I have done is to place my code that I want my action to be done upon inside of an asp:Panel. With the panel you can set the attribute of "DefaultButton" to a button inside of the panel, and clicking the button (or pressing "enter") will fire that button's click event. I've found this quite handy when wanting to submit a "form" by pressing enter when I have a master page that contains the only allowable asp:Form.
Hope this helps.
When I first came across this problem, I found the simplest solution for me was to simple COPY and PASTE the Master page and give it a slightly different name, something like:
SiteNameMasterPage 'Default page with FORM tag
SiteNameMasterPageNF 'No Form tag
And then depending on wether I wanted a FORM tag or or not, simply change the masterpage link at the top of my CONTENT-PAGES, like this
<%# Page Title="" Language="VB" MasterPageFile="~/SiteName.master" %>
<%# MasterType VirtualPath="~/SiteName.master" %>
<!-- This masterpage has the default FORM tag -->
or
<%# Page Title="" Language="VB" MasterPageFile="~/SiteNameNF.master" %>
<%# MasterType VirtualPath="~/SiteNameNF.master" %>
<!-- This masterpage does NOT have the default FORM tag -->
and then in the content page, wherever I want to place my form I can include the <form> tag

Resources