I can't find a way to pass a variable declared in my code-behind aspx.js file to the corresponding code-behind.aspx markup file. The error I keep getting is this:
Parser Error Message: Code blocks are not allowed in this file.
My Code-Behind.aspx.js looks like this:
import System;
package Test {
class CodeBehind extends System.Web.UI.Page {
public var my_var;
public function Page_Load(sender, E:System.EventArgs) {
my_var = "This is my_var.";
}
}
}
I compile the code-behind file manually like this:
jsc.exe /t:library /out:bin\codebehind.dll codebehind.aspx.js
The Code-Behind.aspx looks like this:
<%# Page Language="JScript" Inherits="Test.CodeBehind" CompilationMode="Never" %>
<HTML>
<HEAD>
<TITLE>Hello World Test</TITLE>
</HEAD>
<BODY STYLE="font-size:12;font-family:arial,verdana,sans-serif;">
<FORM RUNAT="server">
<%= my_var %>
</FORM>
</BODY>
</HTML>
I know there are ASP.NET server controls such as asp:label and all that stuff but all I want is print out the contents of simple variables which serve as placeholders.
I don't want the website to compile everytime it is requested and I would like to keep the CompilationMode option set to "Never" and compile all code manually if possible.
Thanks!
Codebehind
protected string my_var { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
my_var = "Hello";
}
html
<%= my_var %>
Related
This fun.aspx page gives me errors:
I want to code in APSX like as in PHP
<%# Page Language="C#"%>
<html>
<body>
<%
int add1(int i) {
return 1+i;
}
int x = 555;
try {
Response.Write(add1(5));
throw new Exception("error here1<br>\n");
} catch(Exception ex) {
Response.Write("error detected");
}
%>
<h3>Lower</h3>
</body>
</html>
You still to use runat=server.
<%# Page Language="C#"%>
<script runat=server>
protected int add1(int i)
{
return 1+i;
}
</script>
<html>
<body>
<form id="form1" runat="server">
<% { Response.Write(add1(5)); } %>
</form>
</body>
</html>
Joel's comments are very helpful. To do things the ASP.NET way, you should take a look at the ASP.NET website tutorials. Get to know just the basics of Web Forms and MVC because sooner or later you might have to opt for one over the other. I think at this stage, MVC would be a better time investment for you going forward as it will bring you to a closer understanding of HTTP and how the Web works.
With Web Forms, as with MVC, we should really aim to keep the code separate from the ASPX markup. Microsoft is pushing this in the Core version of MVC going forward with the use of MVC Razor Pages.
In the spirit of keeping presentation and functionality separate with Web Forms, you really should be using the code-behind file for the logic:
ASPX:
<asp:Label ID="totalLabel" runat="server"></asp:Label>
CS:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int x = 555;
totalLabel.Text = AddInteger(x);
}
protected int AddInteger(int i)
{
return 1+i;
}
}
Im working on an e-commerce platform which supports multiple stores on different domains. The backend is complete (for now) and I'm now starting the front-end part. Since the platform supports multiple stores I need some kind of templating system and I haven't quite figured out what's the best way to do this.
This are my requirements:
I don't want to rebuild my solution to add a new template
Templates are stored in /Templates/TemplateDirectoryName
I want to be able to use (predefined) usercontrols inside the templates.
I use URL routing and only have 1 Default.aspx page which controls which page template and additional code needs to be loaded.
This is what I came up with so far:
In my template directory i have templates created with master pages (A homepage master file, a default master file, and sub-master files referencing the default master file...for product detail, browse, search etc)
My Default.aspx page picks the right template based on routing values
While this way works I don't think it's very practical but the more I think about it the more I come to the conclusion that there are not so many other options to go around this. I think this is what I want to ask: Is there a way to use usercontrols in a template and have the template completely seperated from the application so users can create templates without having to worry about the site's namespace and structure?
Kind regards,
Mark
Since you are referencing a folder for templates, wouldn't it be possible to just change the .aspx files in the folder and asp.net shall pick up the template based on the url path that you've mentioned? I think that is possible in asp.net.
Also, Frameworks like DotNetNuke, Sharepoint, Joomla etc. have the similar concept. You can avail their features.
My proposed solution is below. It has a few constraints, like all master pages need to implement the same set of placeholder controls (not surprising). Take a look and let me know what you think.
I setup my folder structure like this:
Website -> Templates -> TemplateFolder (named same as the template)
Website -> Templates -> UserControls (User controls are stored in a non-template specific folder)
I defined a simple Template configuration class which we can store/save/load a basic template deffinition:
public class Template
{
public string TemplateName { get; set; }
public string UserControlName { get; set; }
public string MasterPageName { get; set; }
public string TemplateFolder
{
get
{
return GetTemplateFolder(TemplateName);
}
}
public string TemplateConfigFile { get { return GetTemplateConfigFile(TemplateName); } }
private static string GetTemplateFolder(string name)
{
return HttpContext.Current.Server.MapPath("~/Templates/" + name + "/");
}
private static string GetTemplateConfigFile(string name)
{
return GetTemplateFolder(name) + "/" + name + ".config";
}
public Template()
{
}
public void Save()
{
XmlSerializer xs = new XmlSerializer(typeof(Template));
if (!Directory.Exists(TemplateFolder)) Directory.CreateDirectory(TemplateFolder);
using (FileStream fs = File.OpenWrite(TemplateConfigFile))
{
xs.Serialize(fs, this);
}
}
public static Template Load(string name)
{
if(!File.Exists(GetTemplateConfigFile(name))) return null;
XmlSerializer xs = new XmlSerializer(typeof(Template));
using (FileStream fs = File.OpenRead(GetTemplateConfigFile(name)))
{
Template t = (Template)xs.Deserialize(fs);
return t;
}
}
}
You can build some bare xml code to get started with by running the code below:
Template t1 = new Template() { TemplateName = "Template1", MasterPageName = "Child1.master", UserControlName = "uc1.ascx" };
Template t2 = new Template() { TemplateName = "Template2", MasterPageName = "Child2.master", UserControlName = "uc2.ascx" };
t1.Save();
t2.Save();
I created a basic master page. This page will probably never be used except to give your default page the basic placeholders. All of your master pages should have the same set of placeholders as your base one so that your pages can use them all interchangably. Notice I left a placeholder for our user control.
<%# Master Language="C#" AutoEventWireup="true" CodeFile="BaseMaster.master.cs" Inherits="Templates_Masters_BaseMaster" %>
<!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>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="cphHeader" runat="server">
</asp:ContentPlaceHolder>
<asp:ContentPlaceHolder id="cpUserControl" runat="server">
</asp:ContentPlaceHolder>
<asp:ContentPlaceHolder id="cphFooter" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Now I create a basic aspx web page that uses the above master page.
<%# Page Title="" Language="C#" MasterPageFile="~/Templates/Masters/BaseMaster.master" AutoEventWireup="true" CodeFile="DefaultTemplated.aspx.cs" Inherits="DefaultTemplated" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphHeader" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="cpUserControl" Runat="Server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="cphFooter" Runat="Server">
</asp:Content>
In the codebehind we'll setup the basic templating. This sets the masterpage and adds a pre-defined user control to the content placeholder for user controls. If you wanted you could just make a panel or something and add it to that fixed control, but I thought you might appreciate seeing how to make it work with masterpages.
public partial class DefaultTemplated : System.Web.UI.Page
{
private Template PageTemplate
{
get
{
if (_tLoaded == null)
{
string template = Request.QueryString["template"];
if (string.IsNullOrEmpty(template)) return null;
Template t = Template.Load(template);
_tLoaded = t;
}
return _tLoaded;
}
}
private Template _tLoaded = null;
protected void Page_Load(object sender, EventArgs e)
{
if (PageTemplate != null)
{
//cpUserControl is the name of my usercontrol placeholder
((ContentPlaceHolder)Page.Form.FindControl("cpUserControl")).Controls.Add(
Page.LoadControl("~/Templates/UserControls/" + PageTemplate.UserControlName));
}
}
protected void Page_PreInit(object sender, EventArgs e)
{
if (PageTemplate == null) return;
this.MasterPageFile = "~/Templates/" + PageTemplate.TemplateName + "/" + PageTemplate.MasterPageName;
}
}
If you had a template named "Template1" you could use it by calling "Default.aspx?template=Template1". Since you are using URL rewriting you would use the rewriting to pass the template name as a parameter to the page.
Another option that could be combined with the above would be the use of Page.ParseControl. Using this you could store your raw asp.net designer code (designer only) in a database or raw text file. Then you could instantiate it load it like this:
//where pnl1 is a Panel on the page. Page.ParseControl just returns a control object, so use it anywhere.
pnl1.Controls.Add(Page.ParseControl("raw asp.net designer code here."));
One great thing about this is that nested controls work great too.
I don't know if I understand correctly:
If you don't want to rebuild, then I can tell a CMS concept is best suitable for you.
You can store your templates as an HTML in database and from DB you can fetch it back,
You can give an admin functionality with editor to edit your template online also.
I have written a function scroll() in code my behind, and called it using <% Response.Write(scroll()); %> in ASPX page. Function is working properly but in Internet Explorer it shows Error on Page message at corner.
I also tried <%=scroll() %> to call it, still showing error on page message.
Can anybody tell me another way to call function?
Plz help.
Thanks.
I think you are doing some thing wrong, We can call server side function in code behind file like:
Default.aspx
Form tag start
Div start
<%= Scroll() %>
Div end
Form tag closed
Default.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string Scroll()
{
return "test";
}
}
try it out its working and match it with your code.
I'm embarrassed to ask this here because it's clearly been duplicated several times already on StackOverflow. I've read a lot of stuff including:
http://msdn.microsoft.com/en-us/library/xxwa0ff0
http://msdn.microsoft.com/en-us/library/c8y19k6h.aspx
http://www.velocityreviews.com/forums/t110056-cannot-access-strongly-typed-properties-in-master-page.html
I think I've done exactly what those article say, but it's not working for me.
Here's the top of my master page, named "MasterNoNews.master":
<%# Master Language="C#" %>
<%# Import Namespace="MyMediHealth.DataAccess" %>
<%# Import Namespace="MyMediHealth.DataAccess.Containers" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public virtual UserContainer CurrentUser;
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
CurrentUser = new MembershipQueries().getUserFromUserIdName(Page.User.Identity.Name);
}
</script>
Here's the top of my child page, named "MyProfile.aspx":
<%# Page Title="" Language="C#" MasterPageFile="~/MasterNoNews.master"
AutoEventWireup="true" CodeBehind="MyProfile.aspx.cs"
Inherits="MyMediHealth.Interface.MyProfile" %>
<%# MasterType VirtualPath="~/MasterNoNews.master" %>
Here's the code-behind on my child page, named "MyProfile.aspx.cs" that's not working:
using System;
using System.Web.UI;
using MyMediHealth.DataAccess.Containers;
using MyMediHealth.DataAccess;
namespace MyMediHealth.Interface
{
public partial class MyProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// doesn't work
UserContainer user = Master.CurrentUser;
// also doesn't work
UserContainer user = ((MasterNoNews)this.Master).CurrentUser
}
}
}
In the first case, VS is telling me System.Web.Ui.MasterPage does not contain a definition for CurrentUser. In the second case, VS says the type or namespace 'MasterNoNews' could not be found.
What am I doing wrong?
You'll probably still need to move the master page's code to the code behind, but if you put this,
<%# MasterType VirtualPath="~/MasterPages/Site.master" %>
on the aspx page you'll be able to access the master page's public methods directly without all that casting. Like so:
UserContainer user = Page.Master.CurrentUser
If you're using the master page's code from loads of child pages then I'd create an interface and have the master page implement it.
This will not work because you have created properties within Master page (and not code-behind). Typically, master page code would get compiled dynamically and a class name (depending on file name) will be created in a temporary assembly. As you are not reffering to this generated class name within temp assembly, you get error. Correct way will be to have code behind file for the master. For example, master will be
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="MasterNoNews.master.cs" Inherits="[Your Namespace].MasterNoNews" %>
And in code-behind file (MasterNoNews.master.cs) have your properties:
namespace [Your Namespace]
{
public partial class MasterNoNews : System.Web.UI.MasterPage
{
public virtual UserContainer CurrentUser;
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
CurrentUser = new MembershipQueries().getUserFromUserIdName(Page.User.Identity.Name);
}
}
}
Now the second syntax would work i.e.
UserContainer user = (([Your Namespace].MasterNoNews)this.Master).CurrentUser
I have a web page where it will input an excel/CSV file from the user and read the data from it and import to DB.While inserting each record.I just want to show the details about the record being inserted to the user.(Ex : Client Details of A is adding...)
Try this... Set the output to unbuffered (Response.BufferOutput), and include some javascript in your page that updates the UI as you see appropriate. For example, it might update a SPAN with a percentage complete or the details of the record you are processing. Then in your server code, output <script> tags that call the Javascript function from the Render override. Make sure you call Flush() at the appropriate times, and also Flush the base code after it Renders... The JS function calls should get sent down at the appropriate times and executed on the client, resulting in an updating page.
For example... Your HTML page might look like this:
<%# 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>
<script type="text/javascript">
function UpdateScreen(t) {
document.getElementById('output').innerHTML = t;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id='output'></div>
</div>
</form>
</body>
</html>
<script type="text/javascript">
UpdateScreen('hello');
</script>
and your codebehind will look like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void Render(HtmlTextWriter writer)
{
Response.BufferOutput = false;
base.Render(writer);
Response.Flush();
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);
Response.Write(string.Format("<script type='text/javascript'>UpdateScreen('{0}');</script>", i * 10));
Response.Flush();
}
}
}
}
I know this is an old question, and the owner of it may have moved on a long time ago. Anyway:
The proposed solution will not work on ASP.NET MVC. And if you ask me, which you don't, I'll say this is not the cleanest solution to the problem:
Here's a jQuery one,
And here's an IFrame one.