ASP.Net Page Template and using asp tag in rendered pages - asp.net

I want to use page templating in ASP.Net (Visual Studio 2012 with .Net 4.0).
The base page emits the basic template inclusive of the body, html, form, and other tags. That means the rendered pages just have what goes inside the body part. The template adds the header and footer. Although I have not finalized a design, I am looking at a concept documented here. (Yes, I know that coding practice is to not give links to pages, which can go away, but I do not want to side track the question.)
The part of each page is:
<%# Page language="c#" Codebehind="AdvancedPageInheritance.aspx.cs" AutoEventWireup="true" Inherits="PageInheritanceSample.AdvancedPageInheritance" %>
Anything after that first line is part of the body.
If I drag and drop controls onto the form, VS2012 emits code such as:
<asp:CheckBox ID="CheckBox2" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" />
<asp:Button ID="Button2" runat="server" Text="Button" />
VS2012 automagically emits the warning, "Unrecognized tag prefix or device filter 'asp'."
One thought is to simply add in the body stuff programatically, but that is a page. I rather use the GUI.
How can I avoid the warning? Is there a better way to do templates? That author wrote the article 10-years ago, so things might have changed since then. The warnings are understandable, but in error, as there is a form, body, and html tags, just not directly visible.
(I just answered my question by catching a phrase in Vs2012 and researching it a bit. Master Pages are the answer. Obviously, Microsoft must have added that with either VS2008 or VS2010. I will leave this post, as others, like me, may not know the concept "Master Page" and may reserach page templates, just like I did. I hope that this post says other people time. Google should hopefully pick up on ASP.Net and Page Templates.)

Ideally you would use the MasterPage for laying out your main template.
Your Content pages would then have the appropriate <asp:Content /> controls, where you add your content. To add a content page you would add a new 'Web Form' item in Visual Studio and, by selecting the 'Select Master Page' checkbox, you can choose the master page the content page should use.
See Here for a tutorial on Master Pages
Then you would use a BasePage for site-wide code; for example anything that has logic needed on most pages. Your Content pages would inherit this BasePage
As a side-note, see this page Unrecognized tag prefix or device filter 'asp' in VS2012 with regards to your "Unrecognized tag prefix or device filter 'asp'." message

Related

asp.net: Handling form data in Visual Studio 2010

Climbing the learning curve for creating asp.net webform pages with Visual Studio 2010 (VB).
I had written a fairly complicated .aspx page with form controls, including textboxes and buttons, etc. I never thought to place the form controls inside a <form> block. Instead, all the controls include the "runat" directive; for example, <asp:textbox id="txtUserName" runat="server"> etc. In the codebehind I access the data with strUserName = txtUserName.text. This seems to work just fine.
Now, though, I received some form pages from our contracted "professional" web developer wherein the form code is all enclosed in a <form runat="server">block, and none of the controls include the runat directive. Accessing the data from these controls is a little different: It uses the <input type="text name="txtUserName" id="txtUserName" /> method, and accessing the data in the codebehind
is strUserName = Request.Form("txtUserName").ToString.
My method seems to work fine, but I am wondering if there is a difference in behavior or reliability between my method and his. Even though my way works, am I doing it wrong?
Mine is based on online research I have done to learn this stuff, and I don't remember seeing anything that looked like his. However, just today I see places that are saying that on .aspx pages, form controls MUST be enclosed in a <form> block (i.e., this page at w3schools.com).
Can anyone clarify this for me?
Thanks for your help!
You're not doing it incorrectly (you're using my preferred approach) but your inputs should still be in an enclosing Form tag.
He's using HtmlControls (System.Web.UI.HtmlControls namespace) and you're using web controls (System.Web.UI.WebControls.) Your controls provide better functionality on the server (viewstate and accessing via server code) and his approach is lighter weight.

Can I set the language of a web page using ASP.NET resources but no code behind?

I have a kendo single page application that I need to localize. I tried using Javascript to translate text parts, but it gets complicated when translating non HTML bits like templates (inside script tags) and properties like "data-title".
Next I tried changing the extension to .aspx and using ASP.NET resources, as in this example:
<!-- logout -->
<div id="logout" data-role="view" data-layout="layout-logout"
data-title="<asp:Literal ID="Literal1" runat="server" Text="<%$ Resources:TextStrings, Logout%>" />"
data-before-show="myproject.logout">
<div style="padding: 50px 0; text-align: center;">
<p id="lang_LoggedOut"><asp:Literal ID="Literal2" runat="server" Text="<%$ Resources:TextStrings, Logout_Success%>" /></p>
</div>
</div>
This works to some extent, as the <% resources %> bits get replaced.
However I had to transfer login to a separate .aspx page to apply the language, after login (and discovering user culture), but before single page app load.
The login page calls the customary:
protected override void InitializeCulture()
to set the culture, and then redirects to the main app page.
As far as I can make out, the InitializeCulture is ignored, but the page is rendered with the strings from the resource files, sometimes in one language, sometimes in another.
How does ASP.NET decide what culture to apply, and how can I control that choice?
Notes:
failing this, the kendo people seem to suggest having one page for each language, which rather goes against my DNRY inclinations.
Code behind and inline code (<%Page%> directive) are in my experience incompatible with kendo. If I understand right page events get stolen by one another. Kendo is compatible with MVC, but I must learn MVC first, and then get resource files to work with MVC.
The short answer is yes. I have seen it work with VS2010 and IIS 7.5.
The page with no code behind must have an .aspx extension.
the language selection must happen on another .aspx page with code-behind. Call InitializeCulture() here
from this page you must go to the main page using Server.Transfer. See: Server.Transfer Vs. Response.Redirect
Server.Transfer will keep the settings and context you set, and apply the language to the page with no code-behind while the user navigates the page.

asp.net - Use ascx as a layout template

This is my layout template (ascx without code behind)
<%# Control Language="C#" AutoEventWireup="true" Inherits="ws.helpers.LayoutUC" %>
<div>blah blah blah</div>
<ws:Panel runat="server" ID="left"></ws:Panel>
<ws:Panel runat="server" ID="main"></ws:Panel>
<ws:Panel runat="server" ID="right"></ws:Panel>
Modules will be added into ws:Panel later.
I also allow my user create their own ascx file to custom their page layout. And because of this i do a string replace all dangerous part like script tag (runat="server"), all asp.net html tag, <%, <%#, <#.... from their custom.
Im not worry about XSS, so dont comment on it, and ask why?
I want know your thinking about this. Is is safe? Is it scalable? Is it standard or a bad way?
Have a look at the INaminingContainer Interface http://msdn.microsoft.com/en-us/library/system.web.ui.inamingcontainer.aspx.
<asp:YourControl>
<LeftColumn>
<asp:Literal ID="literal1" runat="server" Text="User created literal" />
</LeftColumn>
</asp:YourControl>
In the .ascx from the users, they register your control and insert asp.net code into properties. In the 'YourControl' class you create placeholders and insert the markup set to a specific property into these placeholders. (e.g. everything between <LeftColumn> and </LeftColumn> will the inserted into
<asp:Placeholder ID="PlaceholderLeftColumn" runat="server"/>
Edit: I summed some of the TemplateContainer issue up and posted it here: http://www.tomot.de/en-us/article/2/asp.net/how-to-create-an-asp.net-control-that-behaves-as-a-template-container-to-nest-content-via-markup
You are allowing user-uploaded content; this is inherently unsafe and there are whole books dedicated to best practices. Given that you are doing it anyway, as long as you make sure you scrub the input, is it scalable? You are allowing creation of user-uploaded files on your site. How many will there be? How many users? What about load-balancing? This solution will not scale for many users, files, or servers.
It sounds like you are trying to create a simple CMS. Why not use one that exists currently, or adopt parts of an open source solution?

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

Form Elements in ASP.NET Master Pages and Content Pages

OK, another road bump in my current project.
I have never had form elements in both my master and content pages, I tend to have all the forms in the content where relevant.
In the current project however, we have a page where they want both. A login form at the top right, and a questions form in the content.
Having tried to get this in, I have run in to the issue of ASP.NET moaning about the need for a single form element in a master page. TBH, I really dont get why this is a requirement on ASP.NET's part, but hey ho.
Does anyone know if/how I can get the master and content pages to contain form elements that work independantly?
If not, can you offer advice on how to proceed to get the desired look/functionality?
Thought I would review some of my outstanding questions and see if I can close some of them off.
This one was an interesting one. I outright refused to believe you can only have one form on an ASP.NET page. This to me made no sense. I have seen plenty of webpages that have more than one form on a web page, why should an ASP.NET page be any different?
So, it got me thinking.
Why does a ASP.NET page need a form element?
ASP.NET pages try to emulate the WinForms environment, by provided state persistance through the PostBack model. This provides an element of state to a stateless environment. In order to do this, the runtime needs to be able to have the ability to maintain this state within each "form". It does this by posting back data to itself. It's important to note that:
There is nothing really fancy about a PostBack.
It uses a HTTP form and POST, the same as any other form, from any other stack.
Just because it looks like it might be doing something special, its not, all that happens is it POST's back with some info about what caused it, so you can do things like handle client-side events, in server-side code.
So why only one?
This to me was the million pound question (I am British). I understand that ASP.NET needs this, especially if you are using ASP.NET server controls, but why the hell can't I make my own additional forms?
So, I thought screw it, just make your own form!
And I did. I added a bog-standard, simple form with a submit action of "#". This then performs a POST to the current page, with the Form data for the given form in the request.
Guess what? It all worked fine. So I ended up with:
A master page, with a HTML form in
This form posts back to the current page (basically the page using the master).
In the Page_Load code-behind for the master, I then added code to check the request to see what data was passed in the request. If it contains data (say a hidden field) then I know the post was sourced from the Form on the master page, if not, then it is most liekly a PostBack from content, and can be ignored.
I then surrounded the Content tags with <form runat="server" id="aspNetForm"...> </form> tags. This meant that all content pages automatically had a form to work with.
This provided me with a relatively simple, clean solution to my problem. My login form works fine in tandem with all the content forms created, some of which are complex forms, others use lots of server controls and many PostBacks, and so on.
I hope this helps others.
the form tag itself is in the MasterPage, as such, you can code any asp.net server controls onto the master page that you wish. And you can write up the processing logic for those server controls on the master page's code behind file.
So, in your example, you can have the login controls on the upper right of the master page, and then have the authentication logic in the code page for the MASTER PAGE, not your content page.
This allows you to have the login controls on every page, and maintain that processing, as well as maintain the content controls and their processing on their individual pages.
Everyone else has already mentioned that you can only have a single form element in a given ASP.NET page, and that it would be contained in the master page. So far, so good. But I don't think that helps you get fully where you want to be ...
In your master pages, you've (I assume!) defined asp:ContentPlaceHolder controls. Your pages which use the master then have corresponding asp:Content tags. All your page content must go in these corresponding asp:Content tags.
Once in that tag, they are part of the master page's form. The master page can respond to events from its own controls, and the pages themselves respond to events from their own controls, and you're set.
If you need the page to interact with the master page, you can access it via the Page.Master property. To interact with any publicly-visible code (methods, properties, etc.) from the master page, you'd cast this property to the correct type, and access the publicly-visible code from there.
That should get you where you need to be in this scenario. (It's worked for me on multiple sites!)
Rob,
Interesting solution. I don't see any problem with what you are doing. The problem some may encounter however, is if they try to do this with 2 server forms. There's no rule in ASP.NET that you can't have more than 1 HTML form on a page, just that you can't have more than one "runat='server'" form on the page. Obviously you've found a pretty easy way of meeting your needs.
I've found that for the most part dealing with a single form is not a problem because the ASP.NET framework basically separates everything for us with naming containers. But in your initial post comment you hit on the important factor that was absent yet critical to the essence of the original question: enter key behavior. That always throws a monkey wrench into the works.
If you were to use a standard "all encompassing" server form, couldn't you capture the right action using a textbox text changed event? Of course, if the user changed both values before hitting enter on either you would get strange behavior. And I think the core problem with the enter key is that once you have more than one submit input on an HTML form, hitting ENTER in a textbox doesn't do anything. Only when there is a single INPUT element does the enter key cause one to be "clicked".
None of the previous answers gave a code example. Here's a simplified version of the Visual Studio 2012 Site.Master that illustrates how to do this:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site - Copy.Master.cs" Inherits="WebApplication1.Site1Master" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>This is a title</title>
<asp:ContentPlaceHolder runat="server" ID="HeadContent" />
</head>
<body>
<form runat="server">
<header>
<div class="content-wrapper">
<div class="float-right">
<section id="login">
<asp:LoginView runat="server" ViewStateMode="Disabled">
<AnonymousTemplate>
<asp:ContentPlaceHolder runat="server" ID="AnonContent" />
</AnonymousTemplate>
<LoggedInTemplate>
<asp:ContentPlaceHolder runat="server" ID="LoggedInContent" />
</LoggedInTemplate>
</asp:LoginView>
</section>
</div>
</div>
</header>
<div id="body">
<asp:ContentPlaceHolder runat="server" ID="FeaturedContent" />
<section class="content-wrapper main-content clear-fix">
<asp:ContentPlaceHolder runat="server" ID="MainContent" />
</section>
</div>
</form>
</body>
</html>
So you have everything wrapped by a single Form element, so you can place controls in the master page, yet your content pages can also use controls.
You can only have one form on an ASP.NET page. One way to handle this is to put an event handler on the login button in the master page. The handler will validate the user and redirect to the same page on success (to correctly run the Page_Load handler, which is run before event handlers).
I solved the "clicking the return key in the login sub-form causes the main form to submit" problem in my current project by embedding an iframe into the master page. The iframe pointed to the login.aspx page which authenticated the user.
<iframe id="login" src="login.aspx" frameborder="0" enableviewstate="false" scrolling="no" runat="server"></iframe>
(form some reason I needed the closing /iframe tag otherwise design view got confused)
You can access MasterPage controls from the aspx form by:
add the detractive tag to the aspx form <%# MasterType VirtualPath="~/Site.Master %>
and in the code behind use Master.FindControl(); to get the control by ID
for Example if you want to get the
Control form = Master.FindControl("form")
now you can use the master page's form in your code.
I hope this help.
Salve! In a similar thread, I posted an answer that might help you. You can use jquery to add content to an empty div. That content can include form tags, and even a submit function independant of anything the server-side code is doing. The only downside to this is if the user does not have javascript enabled!
Instead of reposting the same answer (and the code too), here is the link:
Jquery Ajax loading form on asp.net webform
This is a limitation of ASP.NET
ASP.NET is designed to have one form per page and only one form. When it was originally designed that was not a problem.
However since then this has been identified as a huge problem with accessibility.
Microsoft Fix for this was ASP.NET MVC, if you are able to I would suggest considering moving to ASP.NET MVC as it solves a large number of problems with ASP.NET
You can have more than 1 form. (just only 1 visiable at a time) codeline 1 = form 1 visable / form 2 hidden . Code 2 Form 2 visable / form 1 hidden. = solved (this is great for static contact forms as well
no, you can only have one asp.net form per page.
That has been the rule since 1.0
They should both share the same form

Resources