Is there any way to inject JQuery into every page on an ASP.Net site without adding the script tag to every page individually?
Using Master Page is easy way to do that. But if you already constructed your site, implementing this with master page may be mass of work. Instead of that you can create BasePage class which is inherited System.Web.UI.Page as below:
Check this out
public class BasePage:System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
// Define the name, type and url of the client script on the page.
String csname = "ButtonClickScript";
String csurl = "~/script_include.js";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the include script exists already.
if (!cs.IsClientScriptIncludeRegistered(cstype, csname))
{
cs.RegisterClientScriptInclude(cstype, csname, ResolveClientUrl(csurl));
}
base.OnInit(e);
}
}
Every page which derived from BasePage includes that script source dynamically. (see below)
public partial class Default : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
//Some code ...
}
}
But, if you didn't create your site yet, Master Page is the easiest way to do that.
Use Master Page. Inject the JQuery into MasterPage only, all your aspx pages will use the MasterPage.
use document.write
Related
I have the following that I'm using in every page:
public partial class Pages_MyPage : System.Web.UI.Page
{
ViewUserPreferencesModel TheUserPreferences;
Protected void Page_Load(object sender, EventArgs e)
{
TheUserPreferences = (ViewUserPreferencesModel)Session["SessionUserPreferences"];
And then I use a Page Method like this:
[WebMethod]
public static string GetAppointements(string DateInput)
{
ViewUserPreferencesModel TheUserPreferences = (ViewUserPreferencesModel)HttpContext.Current.Session["SessionUserPreferences"];
My question is this: Do I need to include the statement that loads user preferences when I run the page method or are the statements in the Page_Load event triggered when the page method is called, and if they are, will the variable be populated?
Thanks.
No, Page Methods do not follow the ASP.NET page lifecycle. However, even if they did, your TheUserPreferences variable won't be accessible in the static context.
I have a BasePage having common functionality required by all pages. I have defined a PreRender() event on page base. There are 2-3 pages which does not require this functionality. Can i unsubscribe to PreRender() event of BasePage from my .aspx page. I tried casting BasePage to Page
(PageBase as Page).PreRender -= OnPreRender(new EventArgs());
but it says PageBase is a type but is used as a variable. How to achieve this. Please suggest.
I am adding PreRender() event as follows:
public PageBase()
{
this.PreInit += new EventHandler(PageBase_PreInit);
this.PreRender += new EventHandler(PageBase_PreRender);
}
Your example looks close. What if you try:
base.Page.PreRender -= new EventHandler(Page_PreRender);
This assumes you added the event using:
base.Page.PreRender += new EventHandler(Page_PreRender);
Another option is override the OnPreRender method in your BasePage and use a protected field to check if it should be done. For the three pages, set it to false:
protected bool _useMyCustomPreRender = true;
protected override void OnPreRender(EventArgs e)
{
if (_useMyCustomPreRender)
{
// do my logic here
}
base.OnPreRender(e);
}
Here is my master page code behind:
namespace mysite.MasterPages
{
public partial class Main : System.Web.UI.MasterPage
{
public bool isLoggedIn;
protected void Page_Load(object sender, EventArgs e)
{
isLoggedIn = Request.IsAuthenticated; // Is the user currently logged in
}
}
}
Here is my register page code behind:
namespace mysite
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (((MasterPage)Page.Master).isLoggedIn)
{
Response.Redirect("default.aspx");
}
}
}
}
I'm trying to make the isloggedIn accessible to all pages using that as a master page! I get errors like:
Error 2 The name 'isLoggedIn' does not exist in the current context
Error 3 'System.Web.UI.MasterPage' does not contain a definition for 'isLoggedIn' and no extension method 'isLoggedIn' accepting a first argument of type 'System.Web.UI.MasterPage' could be found (are you missing a using directive or an assembly reference?)
Any help appreciated.
add <%# MasterType VirtualPath="~/Main.master" %> to your page markup.
and your this.Master's type becomes AlphaPack.MasterPages.Main instead of System.Web.UI.MasterPage. So you will be able to access it without cast:
this.Master.IsLoggednIn
Currently you need do next:
((AlphaPack.MasterPages.Main)this.Master).isLoggednIn
And better - create a property. And hold data not in variable but in ViewState (read Control State vs. View State):
namespace AlphaPack.MasterPages
{
public partial class Main : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
this.IsLoggedIn = Request.IsAuthenticated;
}
public bool IsLoggedIn
{
get { return this.ViewState["isLoggedIn"] as bool? ?? false; }
set { this.ViewState["isLoggedIn"] = value; }
}
}
}
And what about code-behind. I recommend to use Web App project, not Web Site project (which is out-of-date)!
Next markup syntax is used. Web app:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="MyPage.aspx.cs" Inherits="MyNamespace.MyPage" MasterPageFile="~/MyMaster.master" Title="MyTitile" %>
and web site:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" MasterPageFile="~/MyMaster.master" Title="MyTitile" %>
if (((MasterPage)Page.Master).isLoggedIn)
Should be
if (((mysite.MasterPages.Main)Page.Master).isLoggedIn)
You cast Master to a MasterPage type (which is useless as it is already a MasterPage). But MasterPage doesn't contain the property isLoggedIn. That's why you can't access it.
So, just cast the Master property to the right type, in your case mysite.MasterPages.Main
The problem here is that your are declaring isLoggedIn within an inline code-block, so it will only be scoped to within that block.
You'll need to add it as a variable within the code-behind class or within <script runat="server"></script> tags, if adding the server-side code inline, i.e. (trimmed down for brevity):
<script runat="server">
public bool IsLoggedIn;
protected void Page_Load(object sender, EventArgs e)
{
IsLoggedIn = Request.IsAuthenticated;
}
</script>
You could then access the master page in subpages like so:
<%
if (((MasterPage)Page.Master).IsLoggedIn)
{
}
%>
However, I'm not sure that this is the best way to achieve what you want. I would probably take that logic out of the master page and stick it in a purpose built authentication class or service.
Usually one would store such Global 'states' inside a session variable. Are passing it around as a query string parameter?
And why are you not putting the code in the code behind?
Edit 1:
Just move this logic:
Response.Redirect("default.aspx");
directly into your masterpage:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated) // Is the user currently logged in
{
Response.Redirect("default.aspx");
}
}
If this is the default behaviour you want for all pages that will be using this Master Page.
Edit 2:
you said in a comment :
and how would i go about accessing the
variable on other pages?
There are 3 ways I can think of:
Query String (Per Page Request)
ViewState (Per Page)
Session Variable (Available Globally)
My problem is this I have a base page that creates content dynamically. There are buttons on my Master Page that fire events that my base page needs to know about. But the OnLoad function on my base page fires before my Button_Command function on my master page. So I either need to figure out a way to load my base page after the Button_Command function has had the chance to set a variable or I must call a function in my base page from the Button_Command function.
Have you considered using strongly typed master pages?
You can also check out my answer to this question.
I believe you can do this with an interface
public interface ICommandable
{
public void DoCommand1(object argument);
}
So the child page implements this interface
public class MyPage : Page, ICommandable
{
public void DoCommand1(object argument) {
}
}
And on the master page
public class Master : MasterPage
{
public void Button_Command(object sender, EventArgs e)
{
if (Page is ICommandable)
{
(Page as ICommandable).DoCommand1(myargument);
}
else
throw new NotImplementedException("The current page does not implement ICommandable");
}
}
It has been a long time since I worked with webforms however, so I can't swear that this works. I seem to recall writing something like this before.
Could you simply encapsulate the logic that is Button_Command into a public method and call that method both from the Button_Command event on the Master Page and from the Load event on the child page? So something like
protected void Page_Load( object sender, EventArgs e )
{
var master = (MyMaster)this.Master;
master.Foo();
}
I have a menu of report links in my master page. I need to append an ID to the end of each whenever the user changes a value on the child page. What's a good way to accomplish this?
UPDATE: I should have mentioned that the child update is happening inside an UpdatePanel, meaning the master page is not reloaded when the change happens.
A MasterPage is really a child control of the page which it controls. You can control a MasterPage like any other control on your page (almost). All you need to do is get a reference to it.
You add a property to the code of your MasterPage, so its code may look something like this:
public partial class _default : System.Web.UI.MasterPage
{
protected string m_myString = string.Empty;
public string myString
{
get { return m_myString; }
set { m_myString = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
Then you have to cast the this.Master property to your MasterPage
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Cast here to get access to your MasterPage
_default x = (_default)this.Master;
x.myString = "foo";
}
}
In response to your UPDATE:
The updated panel could write the ID to a hidden field and the menu events could look for that hidden fields in Request.Form["fieldName"].
Note that you shouldn't fieldName.Text because ASP.NET does a bad job of returning the right value for fields that have been AJAXed.