My master page code looks something like this:
namespace Recipes
{
public partial class MasterPage : System.Web.UI.MasterPage
{
...
public void UpdateUserLogin()
{
NicknameLbl.Text = ((Recipes.BasePage)Page).CurrentUser.Nickname;
}
...
}
}
I want to call the UpdateUserLogin() method from a user control, something like this:
((Recipes.MasterPage)this.Page.Master).UpdateUserLogin();
But for some reason the compiler doesn't know Recipes.MasterPage (are you missing an assembly blablabla).
Sorry I can't show the exact error message, it's in French.
Maybe the problem is that I added the Recipes namespace around MasterPage manually, it wasn't added by VS.
By the way I'm using VS Web Developer Express 2008.
Do you have any idea how I can make this call work?
Both the MasterPage and the UserControl are child controls of the page they are used by. Your UserControl could potentially be used in a page that doesn't use your MasterPage, and so calling UpdateUserLogin() would not be valid.
You can check it like this, however, and make your call conditionally:
if (Page.Master is MasterPage)
{
((MasterPage)Page.Master).UpdateUserLogin();
}
UPDATE
It seems you were already aware of that, sorry. Your question is about the reference not working. What is the namespace of your UserControl?
I would recommend data binding the NicknameLbl to the CurrentUser.Nickname property. Then the NicknameLbl text will get updated automatically if the property changes.
include a MasterType directive at the top of the Content page ASPX file:
'<%# MasterType virtualpath="~/DetailsMaster.master" %>'
include a public method in the Master page
public void UpdateUserLogin(string value)
{
NicknameLbl.Text = value;
}
access the method from the Content page using the Master syntax:
Master.UpdateUserLogin(Some Text");
http://www.codeproject.com/KB/aspnet/Master_and_Contents.aspx
If your project is a Web Site Project (instead of a Web Application Project), then you do not have a project namespace. All code that is referenced from aspx.cs or master.cs files needs to be stored inside the App_Code directory, as the ASP.Net compiler will create several assemblies instead of just 1, and its not predictable which assembly will contain which aspx code.
Update after 1st comment:
The .ascx.cs and .aspx.cs stay where VS puts them. But it you want to reference classes etc, this needs to be placed inside App_Code, e.g. your Recipes.MasterPage or Recipes.BasePage objects.
Related
In my master page I will load some data from the database. I have place it into an asynchronous method. For normal pages I place Async="true" on the top but if I do it on the master page, I have the following error:
myproject.master does not contain a definition for AsyncMode and blablabla...
I've also search on the internet but nothing found for an asynchronous master page. Language I use on background is C#.
Can anyone help me?
The sample uses the new async and await keywords (available in .NET 4.5 and Visual Studio 2012) to let the compiler be responsible for maintaining the complicated transformations necessary for asynchronous programming. The compiler lets you write code using the C#'s synchronous control flow constructs and the compiler automatically applies the transformations necessary to use callbacks in order to avoid blocking threads.
ASP.NET asynchronous pages must include the Page directive with the Async attribute set to "true".
Master File contain master directive.
Master Page inherit MasterPage class of System.Web.UI which does not contain AsyncMode property..So you can't use it at master page.
Normal Page inherit Page class of System.Web.UI which contain AsyncMode.
You can set it in the master page like this. Found solution here:
public abstract class MyBasePage : System.Web.UI.Page
{
public MyBasePage()
{
this.AsyncMode = true;
}
}
Then change the inheritance in the aspx.cs file to something like this:
public partial class WebForm1 : MyBasePage
It can break the system when you set the AsyncMode property in anything else then the constructor.
I have made an ASP.NET application using Notepad++. For this exercise I do not want to use Visual Studio, or any other tool. I want to understand the process.
I have created my website, and it is up and running fine, and all working well.
Now I want to add some C# code behind the pages, both for the master page and for individual pages.
So far, I have a file called Home.aspx, and I want to add a C# file to this.
I have created a file called Home.aspx.cs. Below is the full content of the file:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("LOAD");
Response.End();
}
But when the page loads, this file is not loading. Obviously I am missing something, but I am not sure what. Possibly a reference in my web.config or some other folder, or language reference to tell the page this is C#, or something to tell Page_Load to actually run?
Also, I want to do the same thing for my master page, which is currently called masterPage.master.
So would I make a file called masterPage.master.cs, or is it a totally different way, or can this even be done?
All references to this problem explain how to do this in Visual Studio, which I do not want to use.
You can in fact create an ASP.NET WebForms page without compiling .cs files explicitly.
Home.aspx
<%# Page Src="Home.aspx.cs" Inherits="HomePage" AutoEventWireup="True" %>
Notice that the # Page directive uses the Src attribute instead of the usual CodeBehind attribute.
(Instead of Src, you can alternatively use the CodeFile attribute and mark the code-behind class below partial.)
Home.aspx.cs
using System;
using System.Web.UI;
public class HomePage : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("LOAD");
Response.End();
}
}
masterPage.master
<%# Master Src="masterPage.master.cs" Inherits="MasterPage" AutoEventWireup="True" %>
Same thing, except that you use the # Master directive instead of # Page.
(Again, instead of Src, you can alternatively use the CodeFile attribute and mark the code-behind class below partial.)
masterPage.master.cs
public class MasterPage : System.Web.UI.MasterPage
{
}
(I named the code-behind class MasterPage to match your file name, but to avoid confusion with the built-in ASP.NET MasterPage base class, you may want to choose a different name.)
By adding a CodeFile link to the page as follows:
<%# Page Language="C#" MasterPageFile="~/MasterPage/MasterPage.master" CodeFile="Home.aspx.cs" Inherits="Home" Title="Content Page"%>
and ensuring an inhereits tag is present, it is not necessary to compile the code.
So this is the correct answer
The .aspx, .js and .html files in your asp.net app does not need any compilation, but C# is compiled language, so every .cs file needs to be compiled.
You can use some compiler for that purpose or VS command prompt.
Look at the links as well:
https://msdn.microsoft.com/en-us/library/ms229859%28v=vs.110%29.aspx
https://msdn.microsoft.com/en-us/library/78f4aasd.aspx
https://kencenerelli.wordpress.com/2014/03/08/using-notepad-to-write-c-code/
It needs to be compiled in order to run.
It's possible to call msbuild.exe on your solution from the command line.
https://msdn.microsoft.com/en-us/library/ms164311.aspx
I am trying to add a new custom web control to my asp.net application.
Here is the code for my custom control
using System.Web.UI.WebControls;
namespace MyPersonalCareHealthRecord.classes.extended
{
public class TableHeaderDataCell : TableHeaderCell
{
public string MappedDataField { get; set; }
}
}
In my markup I am using the following code
<dt:TableHeaderDataCell CssClass="HeaderField" runat="server">Test1</dt:TableHeaderDataCell>
After getting some errors, doing some research, and reading this article
http://msdn.microsoft.com/en-US/library/1e9b4c9f(v=vs.80).aspx (along with referencing a book I have on asp.net) I tried adding in a register directive like this one and adjusted my markup to the above.
<%# Register TagPrefix="dt" TagName="TableHeaderDataCell" namespace="MyPersonalCareHealthRecord.classes.extended" %>
However on trying to load the page I get an error: "The directive is missing a 'src' attribute."
I tried changing my directive to:
<%# Register TagPrefix="dt" TagName="TableHeaderDataCell" src="~/Classes/TableHeaderDataCell.cs" %>
and then got error: "The file 'src' is not a valid here because it doesn't expose a type."
After further research and finding this stackoverflow article How to use a Subclassed Control on an ASP.NET Page?
I tried changing my register directive to
<%# Register TagPrefix="dt" TagName="TableHeaderDataCell" namespace="MyPersonalCareHealthRecord" assembly="MyPersonalCareHealthRecord" %>
which resulted in error: "The directive is missing a 'src' attribute."
Adding the src attribute in gave me error: "The 'namespace' attribute is not supported on this directive when a 'tagname' attribute is present."
Removing the tagname attribute gave me errors and removing the namespace tagname did as well....
I realize this was a lengthy question but can anyone help me??? I don't know what I am doing wrong.
Go to add a Webforms User Control.
Once you add it go to code behind of the control (the cs file) and you can put your property there
public string MappedDataField { get; set; }
Save it.
Go to solution explorer and simply drag it in your web form.
In your webform code behind you can access that property.
MyControlName.MappedDataField = "whatever text";
Ok, I believe I have solved it.... I followed the instructions at this link:
http://msdn.microsoft.com/en-us/library/aa310915(v=vs.71).aspx
I created a .dll from my custom control source code file and then made sure the .dll was in the /bin directory in my project. changed my register directive to be:
<%# Register TagPrefix="dt" Namespace="MyPersonalCareHealthRecord.classes.extended" Assembly = "TableHeaderDataCell" %>
(TableHeaderDataCell is the name of the dll file)
At first I got an error about the type being in two places so I had remove the .cs file from the bin directory before it would work. I also had some issues referencing my new type in the actual code behind file so I had to add a reference and browse to the new dll and add a reference to it in my project. After adding the reference I was able to use it in my code behind file.
Is it possible to use global variables in C#? I'm coming from mainly a PHP background so variables are either accessible everywhere or just a global definition away.
My main issue is I have a User class that I built myself to wrap around the current users table on my company's database. I am defining it in the MasterPage but can't seem to access it from the actual pages (I don't know if there's a better word to describe them but they are the pages that inherit the styles and format from the MasterPage)
Any general tips or implementation practices for me?
EDIT: here's some code snippets of what I'm trying to do:
Site.master.cs
public partial class SiteMaster : System.Web.UI.MasterPage
{
public User user = new User();
}
logout.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="logout.aspx.cs" Inherits="logout" %>
<%# MasterType virtualPath="~/Site.master"%>
logout.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
User user = Master.user;
}
}
No, it is impossible. It is possible to create singletons or public static classes, but this is bad practice.
C# was designed for object oriented programming. If you haven't written programs using object oriented paradigm before it can be a bit hard to switch to it in the beginning. OOP (http://en.wikipedia.org/wiki/Object-oriented_programming) is built on three main concepts: inheritance, polymorphism and encapsulation.
You can defined classed apart of the pages/masterpages, it is good practice to define them in the App_Code folder.
Have a public static class and declare public static member variables.
That's what I do when I need some globals, though I try to avoid using them when I can.
If Page is inheriting from MasterPage, then make User property protected in MasterPage and it will be visible to Page.
The Master page class can be accessible to the pages that use it by setting the MasterPageClass in your .aspx page like so:
<%# MasterType TypeName="MyTypeName" VirtualPath="~/MasterPageName.master" %>
It sounds to me like you may just need to put your code in a slightly different place. A typical User class would be accessible to your project through a stand-alone class, and not bundled into a master page or a master type.
I might suggest that you add your User class into a new classfile in the /AppCode directory of your project instead, (User.cs). That would let you have access to it from your pages without having to muck with the MasterType.
See my answer to this question. Non-static class-level variables do no persist once the response is sent to the browser. This is because each Page object is going to be a new instance of the class, not the same one from your last request.
Use the "Session" property instead as I show in the link.
Is your problem, from your page, get to data stored in the masterpage (assuming we're talking about the ASP.Net MasterPage mechanism here)?
If so, you should look at strongly-typed access to masterpages. Basically, what you do is create a public property in your MasterPage class. Then, in your Page, declare the MasterPageFile and MasterType, like this:
public partial class MasterPage
{
public User CurrentUser{...}
}
In your page aspx, declare to use the masterpage and which master type to use.
<%# Page masterPageFile="~/MasterPage.master"%>
<%# MasterType virtualPath="~/MasterPage.master"%>
You will then be able to access the property from within your page class like this:
var user = Master.CurrentUser;
Then, for the question on where to initialize the CurrentUser object, look at the list of page lifecycle events. As you can see, MasterPage.Init fires before Page.Init and MasterPage.Load fires before Page.Load. You can use either MP.Init or MP.Load to make sure the data is ready for when the page events fire, though Init is preferred.
There are at least a couple different ways to achieve what you want:
Use the Application object - It can be used to store things globally and is part of ASP.Net.
Use static classes - This is another option for creating a singleton.
after weeks of having this issue I finally decided to ask for a solution to the following problem:
In the .aspx page you can set
<%# MasterType VirtualPath="~/Mastername.master" %>
This results in an auto generated property in the .aspx.designer
public new Mastername Master {
get {
return ((Masternamee)(base.Master));
}
}
Works perfectly fine. But if I do changes in the .aspx file, the property will be new auto generated and it looks like the following:
public new NAMESPACE1.Mastername Master {
get {
return ((NAMESPACE1.Mastername)(base.Master));
}
}
Compiling will not be possible afterwards, because the class for the MasterPage cannot be resolved at the given namespace.
The masterpage has NAMESPACE1 as namespace.
Every contentpage has the same NAMESPACE1.
The autogenerated property tries to look for the masterpage class in NAMESPACE1.NAMESPACE1 which will fail, due to it does not exist. Of course I can remove the first NAMESPACE1. to make the app compilable again, but it just sucks to do this nearly every time I make changes in the .aspx file.
Is there a way to avoid this problem? The only way I can think of, is to ignore the auto generated property and make a explicit cast everytime I want have access to the masterpage.
Edit: I'm using Visual Studio 2008 Professional SP1.
For some reason the designer believes that the master page is defined in namespace NAMESPACE1, so look at the master page definition (and code behind) to check its namespace has not been modified (possibly accidentally).
If there is nothing obvious, a search in all files (*.cs, *.aspx, *.master, ...) for NAMESPACE1 may be needed.
(This is where using a VCS would help --- you could check the history of changes.)
Actually it's more a designer "feature". ;-)
The Master name used in your designer file will be pulled from your .Master file's Inherits property. So change how you qualify the Inherits attribute, and that will change the class name used when the designer file is created.
I found a solution that works. I won't use the autogenerated property in the designerfile. I'll write my own wrapper property that I do implement in every contentpage.
I had this same problem when I added <%# MasterType VirtualPath="~/TestMaster.Master" %> to my aspx page in SOURCE view. For some reason, the page never created correctly and kept giving me invalid namespace errors until I actually changed to DESIGN view and resized a control and finally the error went away. Somewhere it was using some cached data (even a Build/Clean Solution didn't clear it out) and until the designer recreates the page, it generates that error.
Change
<%# MasterType VirtualPath="~/Mastername.master" %>
to
<%# MasterType TypeName="Mastername" %>
this will work perfectly