Site.master does not see methods in Site.master.cs - c#

I have web app, which has site master 'Adminka.Master'.
Its code:
<%# Master Language="C#" AutoEventWireup="True" CodeBehind="Adminka.master.cs" Inherits="Kaifarik.Pages.Admin.Adminka" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="~/Content/AdminStyles.css" />
</head>
<body>
<form id="form1" runat="server">
<h1>Kaifarik: админ-панель</h1>
<div class="adminContent">
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
<div id="nav">
Управление заказами ### The name 'OrdersUrl' does not exist in current context
Управление каталогом EDOI ## The name 'DishesUrl' does not exist in current context
</div>
</body>
</html>
The problem is that OrdersUrl and DishesUrl methods can't bee seen in Adminka.master.cs file.
Adminka.master.cs code:
namespace Kaifarik.Pages.Admin
{
public partial class Adminka : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string OrdersUrl
{
get
{
return generateURL("admin_orders");
}
}
public string DishesUrl
{
get
{
return generateURL("admin_dishes");
}
}
private string generateURL(string routeName)
{
return RouteTable.Routes.GetVirtualPath(null, routeName, null).VirtualPath;
}
}
}
I created site master and didnt change inherits from default, yet still I get an error:
Error
Here is structure of my project
I tried to regenerate designer file, change paths.
Any help is appreciated.

You can bind the URL with HyperLink.NavigateUrl from code behind.
Adminka.master.cs
namespace Kaifarik.Pages.Admin
{
public partial class Adminka : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
OrdersHyperlink.NavigateUrl = this.OrdersUrl;
DishesHyperlink.NavigateUrl = this.DishesUrl;
}
public string OrdersUrl
{
get
{
return generateURL("admin_orders");
}
}
public string DishesUrl
{
get
{
return generateURL("admin_dishes");
}
}
private string generateURL(string routeName)
{
return RouteTable.Routes.GetVirtualPath(null, routeName, null).VirtualPath;
}
}
}
Adminka.master
Replace your <a> element with <asp:HyperLink>. <asp:HyperLink> will generate <a> element in the HTML.
And apply Target="_self" to open the page in the current frame.
<asp:HyperLink ID="OrdersHyperlink" runat="server" Text="Управление заказами" Target="_self" />
<asp:HyperLink ID="DishesHyperlink" runat="server" Text="Управление каталогом EDOI" Target="_self" />
References:
HyperLink.NavigateUrl
HyperLink.Target

Related

Splitting up WebMethods into multiple files

I previously had a single .aspx.cs file that contained numerous WebMethods. It looked something like this:
// webmethods.aspx.cs
public partial class Default : System.Web.UI.Page {
[System.Web.Services.WebMethod]
public static string Method1() {
}
[System.Web.Services.WebMethod]
public static string Method2() {
}
[System.Web.Services.WebMethod]
public static string Method3() {
}
}
And the corresponding .aspx file, that looked something like this:
<%# Page Language="C#" MasterPageFile="Navigation.master" AutoEventWireup="true" CodeFile="webmethods.aspx.cs" Inherits="Default" Debug="true" %>
I was able to then call my WebMethods successfully using AJAX.
But the webmethods.aspx.cs file was getting very large, and I wanted to split the WebMethods up into different files. So I did that like this:
webmethods.aspx.cs:
// first file
namespace Foo {
public partial class Default : System.Web.UI.Page {
[System.Web.Services.WebMethod]
public static string Method1() {
}
}
webmethods2.aspx.cs:
// second file
namespace Foo {
public partial class Default : System.Web.UI.Page {
[System.Web.Services.WebMethod]
public static string Method2() {
}
}
webmethods3.aspx:
// third file
namespace Foo {
public partial class Default : System.Web.UI.Page {
[System.Web.Services.WebMethod]
public static string Method3() {
}
}
And changed the page directive to Inherits="Foo.Default".
But now, every time I try to access any of the WebMethods in the other files via AJAX, I get an Unknown WebMethod error. The AJAX request is still being sent to the webmethods.aspx.cs file.
Can someone help guide me as to what I did wrong?
WebForm compilation model allows single CodeBehind file for a partial class which compiles into a single .dll. All files in App_code folder also compile in a single file before compilation of .aspx and .aspx.cs. So workaround may look like this.
//Default.aspx
<!DOCTYPE html>
<%# Page Language="C#" AutoEventWireup="true" Inherits="SomeApp.MyPage" %>
<%-- No CodeBehind. inherits external class--%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" ID="lblTest"></asp:Label><br />
<asp:Button runat="server" ID="btnTest" Text="click me" OnClick="btnTest_Click" />
</div>
</form>
</body>
</html>
//App_Code\MyPage.cs
namespace SomeApp
{
public partial class MyPage : System.Web.UI.Page
{
//You need to declare all page controls referred by code here
public System.Web.UI.WebControls.Label lblTest { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
lblTest.Text = "hello world from app_code";
}
}
}
}
//App_code\AnotherFile.cs
namespace SomeApp
{
public partial class MyPage : System.Web.UI.Page
{
protected void btnTest_Click(object sender, EventArgs e)
{
lblTest.Text = "hello world from btnTest_Click";
}
}
}
It should work with [WebMethod]s as well.

ASP.Net User Control data binding error - property does not exist in current context

I am going through a great book learning C# 5.0 and ASP.Net and came across data binding with controls. I have gone through the necessary steps to bind the data but I am receiving a confusing error message as the code below states.
Show.cs //Class for the show properties
namespace BindingExample
{
public class Show
{
public int ID {get; set;}
public String ShowName {get; set;}
}
}
LabelText.aspx.cs //user control code behind
namespace BindingExample
{
public partial class Label LabelText: System.Web.UI.Page
{
protected void load_page(object sender, Event args)
{
Show show = new Show
{
ID = 1,
ShowName = "C# is the Best"
};
//binding
Page.Binding();
}
}
LabelText.aspx //user control markup where the problem occurs.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="LabelText.aspx.cs" Inherits="BindingExample1.LabelText" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="<%# show.ShowName%>"></asp:Label>
</div>
</form>
</body>
</html>
This is where the problem occurs, intellisense is telling me that show.ShowName is not in the current context, I don't know why as first it is exactly what the book presented and also why it would not be since Show.cs class is in the same folder? Any help solving this will be really appreciated. Thanks
Well, as Intellisense indicates, you can't access show. You need to have a field defined as a part of the LabelText class.
(BTW, something is wrong with your class name - is it LabelText or Label? I'll go with LabelText since that's the name you have on the Inherits attribute).
So this is what you need:
namespace BindingExample
{
public partial class LabelText: System.Web.UI.Page
{
protected Show _show;
protected void load_page(object sender, Event args)
{
_show = new Show
{
ID = 1,
ShowName = "C# is the Best"
};
Page.DataBind();
}
}
}
Also, read this answer.
Try making object of Show as public
namespace BindingExample
{
public partial class LabelText: System.Web.UI.Page
{
public Show _show; //this will allow this object to be used in aspx page
protected void load_page(object sender, Event args)
{
_show = new Show
{
ID = 1,
ShowName = "C# is the Best"
};
Page.DataBind();
}
}
}

Add the necessary CSS class to the hyperlink in PageLoad

I want to Show the code that would go in the Page_Load method of Products.aspx that uses the public property and adds the necessary CSS class to the hyperlink
MasterPage Code :
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="MyMaster.master.cs" Inherits="MyMaster.MyMaster" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server">
<title></title>
<style>
ul {
float: left; width: 100%; padding: 0; margin: 0;
list-style-type: none;
}
a {
float: left; width: 6em;
text-decoration: none; color: white; background-color: purple; padding: 0.2em 0.6em;
border-right: 1px solid white;
}
a.selected {
background-color: fuchsia;
}
li {
display: inline;
}
</style> </head> <body>
<form id="form1" runat="server"> <div>
<!--CSS-driven menu --> <ul id="ae" class="selected">
<li><a href="Home.aspx" >Home</a></li>
<li id="Product"><a href="Products.aspx" >Products</a></li>
<li><a href="AboutUs.aspx" >About Us</a></li>
<li><a href="ContactUs.aspx" >Contact Us</a></li>
</ul>
<asp:ContentPlaceHolder id="MainContent" runat="server">
</asp:ContentPlaceHolder>
<asp:ContentPlaceHolder id="FeaturedContent" runat="server">
</asp:ContentPlaceHolder>
</div>
</form> </body> </html>
<script type='text/javascript'>
function mouseUp(element) { element.style.background = 'red'; }
function mouseDown(element) { element.style.background = 'blue'; }
</script>
MyMaster.Master.cs:
namespace MyMaster
{
public partial class MyMaster : System.Web.UI.MasterPage
{
public String anc
{
get { return anc; }
set { anc = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
Product.aspx.cs
namespace MyMaster
{
public partial class Products : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//MyMaster m = new MyMaster();
//Master.MasterHyperlink.
// Master.MasterHyperlink.Navigateurl = "Products.aspx";
Control cntb;
cntb = this.FindControl("ae");
cntb.CssClass = "Selected";
}
}
}
}
You are trying to change the class attribute of an HTML tag in code behind. This won't work unless you add runat="server" to the tag. this.Findcontrol looks for ASP.Net controls and not for HTML controls. You can achieve this with jQuery easily.

Access C# variable from in JavaScript

I am learning ASP.net,
I have a variable in the code behind in c#:
public int hasCar= 1;
and in the aspx file I want to access this variable in javascript function:
function PrintCar( ) {
var ind = <%=this.hasCar%>
alert(ind);
}
but I get error:
does not contain a definition for 'hasCar' and no extension method 'hasCar' accepting a first argument of type 'ASP.vids_aspx' could be
found (are you missing a using directive or an assembly reference?)
what is wrong?
thank you
This works for me:
ASPX Page:
<body>
<script type="text/javascript">
function PrintCar( ) {
var ind = <%=this.HasCar%>
alert(ind);
}
</script>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="PrintCar();"/>
</form>
</body>
Code Behind
public partial class WebForm1 : System.Web.UI.Page
{
public int HasCar { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
HasCar = 1;
}
}
I want to offer a complimentary answer rather than simply copying what other people have said. Personally I write JS from my C# rather than putting markup in the aspx.
I use this extension method:
public static class ClientScriptManagerExtensions
{
/// <summary>
/// Registers an object as a variable on the page
/// </summary>
public static void RegisterObjectAsVariable(this ClientScriptManager mgr, Type type, string variableName, object objectToEncode)
{
mgr.RegisterClientScriptBlock(type,
string.Concat("ClientScriptManagerExtensions_", variableName),
string.Concat("var ", variableName, " = ", new JavaScriptSerializer().Serialize(objectToEncode), ";"),
true);
}
}
Then to call I do:
this.Page.ClientScript.RegisterObjectAsVariable(typeof(MyPage), "myVariable", new { myProperty = 123});
This creates a js object on your page:
var myVariable =
{
myProperty = 123
};
Which you can access via JS. I find this approach much cleaner and it lets you pass all sorts of complex objects to your code.
Have you the following line at start line of your .aspx page ?
<%# Page Language="C#" CodeBehind="default.aspx.cs" Inherits="YOURNAMESPACE._default" %>
I have created test project just for your problem.
Try this code
Aspx Code..
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="test.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<script type="text/javascript">
function PrintCar() {
var ind = <%=this.HasCar%>;
alert(ind);
}
</script>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="PrintCar()"/>
</form>
</body>
</html>
Code behind...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace test
{
public partial class WebForm1 : System.Web.UI.Page
{
public int HasCar { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
HasCar = 1;
}
}
}

ScriptManager not found by UpdatePanel if loaded in BasePage

Platform: asp.net 4.0
I load scriptmanager from a baseclass for custom cdn handling and scripts inserting in pages and other custom things.
The problem is that when I insert an UpdatePanel it doesn't find the script manager because updatepanel search for it to early.
Is there a solution that does not imply removing ScriptManager from the basePage.
this class is from our custom utility dll
public abstract class OurFrameworkBasePage:Page
{
protected override void OnInit(EventArgs e)
{
CurrentScriptManager = BuildScriptManager();
Form.Controls.AddAt(0, CurrentScriptManager);
base.OnInit(e);
}
private ScriptManager BuildScriptManager()
{
return new ScriptManager
{
//some scriptmanager settings
};
}
protected ScriptManager CurrentScriptManager { get; set; }
}
this is site specific basepage
public abstract class SiteBasePage:OurFrameworkBasePage
{
//some custom methods and utility for a specific site
}
the default.aspx page
<html>
<head runat="server"><title></title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Literal runat="server" ID="ltr"></asp:Literal>
<asp:Button runat="server" OnClick="btnOkClick" ID="btnOk" Text="ok"/>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Hopefully you have control over your framework class, as this will fix your issue:
protected override ControlCollection CreateControlCollection()
{
CurrentScriptManager = BuildScriptManager();
ControlCollection pageControls = base.CreateControlCollection();
pageControls.AddAt(0, CurrentScriptManager);
return pageControls;
}
protected override void OnInit(EventArgs e)
{
Form.Controls.AddAt(0, CurrentScriptManager);
base.OnInit(e);
}
Needs to be in both places. First, in CreateControlCollection so that it is created along with all the other controls. Second, in OnInit, because the ScriptManager needs to reside in a form with runat="server"
GuthMD's solution is a great one.
in the meantime i found another solution that accomplish different needs and i write there for reference.
My solution imply that if you want to handle postback with updatePanel you have to put scriptmanager tag in aspx page otherwise scriptmanger will be inserted programmatically for scripts references
protected override void OnInit(EventArgs e)
{
CurrentScriptManager = BuildScriptManager();
base.OnInit(e);
}
private ScriptManager BuildScriptManager()
{
ScriptManager rtn;
var script = Items[typeof (ScriptManager)];
if (script == null)
{
rtn = new ScriptManager
{
EnablePartialRendering = false
};
Form.Controls.AddAt(0, rtn);
}
else
{
rtn = (ScriptManager) script;
}
rtn.EnablePageMethods = false;
rtn.AjaxFrameworkMode = AjaxFrameworkMode.Disabled;
rtn.EnableCdn = true;
return rtn;
}

Categories