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.
Related
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
I have a user control:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="StratPlan.Main.UserCons.WebUserControl1" %>
<div>
<table>
<tr>
<td>title: </td>
<td>
<asp:TextBox ID="TitleTextBox" runat="server"/>
</td>
</tr>
<tr>
<td>strategy id: </td>
<td>
<asp:TextBox ID="StrategyIdTextBox" runat="server"/>
</td>
</tr>
<tr>
<td>company: </td>
<td>
<asp:TextBox ID="CompanyTextBox" runat="server"/>
</td>
</tr>
</table>
</div>
In its code behind:
public partial class WebUserControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
TitleTextBox.Text = ExpTitle;
StrategyIdTextBox.Text = ExpStrategyId;
CompanyTextBox.Text = ExpCompany;
}
public string ExpTitle
{
get { return this.TitleTextBox.Text; }
}
public string ExpStrategyId
{
get { return this.StrategyIdTextBox.Text; }
}
public string ExpCompany
{
get { return this.CompanyTextBox.Text; }
}
}
Then in my page, I have a list view:
<div>
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<uc1:WebUserControl1 runat="server" ID="WebUserControl1" ExpStrategyId='<%# Bind(StrategyId) %>' ExpTitle='<%# Bind(Title) %>' ExpCompany='<%# Bind(CompanyName) %>'/>
</ItemTemplate>
</asp:ListView>
</div>
And I bind the datasource like this in code behind:
public void LoadGridView()
{
localVm.EntityList = localVm.RetrieveMany(localVm.SearchItem);
ItemsGridView.AutoGenerateColumns = false;
ListView1.DataSource = localVm.EntityList;
ListView1.DataBind();
}
But whenever I go to my page, it doesn't give the value to the user control. what am I doing wrong?
The pages Load event is called before data bound controls are bound to their data. Change it to PreRenderComplete or Render like this
public partial class WebUserControl1 : System.Web.UI.UserControl
{
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
TitleTextBox.Text = ExpTitle;
StrategyIdTextBox.Text = ExpStrategyId;
CompanyTextBox.Text = ExpCompany;
}
...
}
have a look at ASP.NET Page Life Cycle Overview
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;
}
}
}
I have a repeater control in a user control. The repeater control has a label and a textbox. A new row is added in repeater control on the click of a button. If i add one row and enter some value in textBox and then again add a new row in the repeater control the value entered in the textbox of first row gets lost.
Can anyone help me out how to retain the value of textbox after postback.
You are losing it because you do not have a If not IsPostBack wrapped around the code that sets the value of the textbox.
So every time you execute the page the value is being reset. Wrap the code that sets the value around ispostback and the new value will not be overridden.
if (!Page.IsPostBack) { // set value }
You may get help from the following link:
http://ranafaisal.wordpress.com/2009/02/17/dynamically-adding-removing-textboxes-in-aspnet-repeater/
I have tried myself and found a solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace RepeaterTest
{
public class Car
{
private string _year;
private string _make;
private string _model;
public string Year
{
get
{
return _year;
}
set
{
_year = value;
}
}
public string Make {
get { return _make; }
set { _make=value;}
}
public string Model
{
get { return _model; }
set { _model = value; }
}
public Car(string year,string make,string model){
_year = year;
_make = make;
_model = model;
}
public Car(){
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
namespace RepeaterTest
{
public class Cars:CollectionBase
{
public int Add(Car car) {
return List.Add(car);
}
}
}
in code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace RepeaterTest
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
Cars cars = new Cars();
Car c1 = new Car("2011", "Marcedez", "Marcedez");
Car c2 = new Car("2012", "BMW", "135i");
cars.Add(c1);
cars.Add(c2);
Repeater1.DataSource = cars;
Repeater1.DataBind();
}
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Add") {
//Car carLastEntered = new Car();
Cars cars = new Cars();
foreach (RepeaterItem item in Repeater1.Items) {
Car car = new Car();
car.Year = ((TextBox)(item.FindControl("txtYear"))).Text;
car.Make = ((TextBox)(item.FindControl("txtMake"))).Text;
car.Model = ((TextBox)(item.FindControl("txtModel"))).Text;
cars.Add(car);
//carLastEntered = car;
}
//cars.Add(carLastEntered);
Repeater1.DataSource = cars;
Repeater1.DataBind();
}
}
}
}
in aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="RepeaterTest.WebForm1" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server"
onitemcommand="Repeater1_ItemCommand">
<HeaderTemplate>
<table cellpadding="0" cellspacing="5">
<tr style="padding-top: 5px;">
<td colspan="6">
<asp:Label ID="lblInstructions" runat="server" Text="Add your cars here:" />
</td>
</tr>
<tr runat="server" id="trHeader" style="font-weight: bold;">
<td>Year</td>
<td>Make</td>
<td>Model</td>
<td></td>
<td></td>
<td></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:TextBox ID="txtYear" runat="server" Width="65"
Text='<%#DataBinder.Eval(Container.DataItem, "Year")%>' /></td>
<td><asp:TextBox ID="txtMake" runat="server" Width="70"
Text='<%#DataBinder.Eval(Container.DataItem, "Make")%>' /></td>
<td><asp:TextBox ID="txtModel" runat="server" Width="70"
Text='<%#DataBinder.Eval(Container.DataItem, "Model")%>' /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr style="padding-top: 5px;">
<td colspan="6">
<asp:Button ID="btnAdd" runat="server"
Text="Add Car" CommandName="Add" />
</td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
Hope this helps. Thanks.
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;
}