Willing to admit I'm a complete .NET newbie, but I have extensive experience in classic ASP, which is making this quite tricky as the whole structure of .net is completely different.
I know I'm meant to use code behind, but for now I'm happy embedding it into the pages because:
Each page is going to be simple, so
there wont be too much mixing up
It's probably too much of a step to
do everything the 'right' way, I'd
rather step up to that slowly as I
get to grips with .net
So excusing my lack of code behind, on this page I am trying to get the ID returned by the querystring "mid" (Menu ID), and then display a different CSS class for the menu button we are currently on. Two menu classes, navButton and navButtonO (over).
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="admin.aspx.cs" Inherits="AlphaPack._Default"
title="Administration"
%>
<script language="C#" runat="server" >
protected int menuID;
protected void Page_Load(object sender, EventArgs e)
{
string menuIDdata = Page.Request.QueryString["mid"];
menuID = 0;
// Check the user is allowed here
if (!Roles.IsUserInRole("Admin"))
{
Response.Redirect("../default.aspx");
}
// Get the menu ID
if (int.TryParse(menuIDdata, out menuID))
{
menuID = int.Parse(menuIDdata);
}else{
menuID = 0;
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="mainHead" runat="server" >
<title>Administration</title>
<link rel="Stylesheet" href="../style/admin.css" />
</head>
<body>
<div class="topMenu">
<div class="navButton<%if(menuID == 0){ response.write("O") }%>">
Admin Home
</div>
<div class="navButton<%if(menuID == 1){ response.write("O") }%>">
User Manager
</div>
<div class="navButton<%if(menuID == 2){ response.write("O") }%>">
Products
</div>
</div>
<br /><br />
<div class="subMenu">
Products Categories
</div>
<br /><br />
Welcome to the Admin
</body>
</html>
Thanks for any help, don't pull any punches.
You should really put your code in the code behind page, there is no value to keeping it in the markup page even if it is simple. Second you are still thinking classic asp and using Response.Write. There is almost no reason to ever use Response.Write, if you are using it in a markup page then you are almost always doing it wrong. Turn your divs into Panel controls which will render out as divs. Then use a simple switch statement to set the CssClass property in the code behind page. You are using int.Parse you should only use this if you are guaranteed to get an int back from parsing the text. If it does not parse it will throw an exception, use int.TryParse instead.
Promote midID to a class variable.
protected int menuID;
protected void Page_Load(object sender, EventArgs e)
{
menuID = 0;
// Check the user is allowed here
if (!Roles.IsUserInRole("Admin"))
{
Response.Redirect("../default.aspx");
}
// Get the menu ID
menuID = int.Parse(Page.Request.QueryString["mid"]);
}
int menuId = 0;
Should be:
public int MenuId{get;set;}
Related
I am designing a Change Request(CR) module for our website, which allows users to raise a CR and submit it for review. A workflow gets generated immediately after raising CR, so, user have to submit it by voting to his activity(Say activity as 'Submit to CCB'). Then I am setting a label's value which is added to master page as 'In Review' I can see label value now, and immediately navigating to next activity(next page). But I could not see the label's value there in next page.
As I am new to implementing master page concept, unable to find out the reason.
WFLCRMaster.master
<%# Master Language="C#" AutoEventWireup="true" CodeFile="WFLCR.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="masterFormMIF" runat="server">
<div id="WorkflowStatus">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UserUpdatePanel" runat="server">
<ContentTemplate>
<asp:Label ID="WorkflowSignoffStatus" runat ="server"> </asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolderMIF" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
And I created a property in WFLCR.master.cs, And added <%# MasterType VirtualPath="~/WFLCR.master" %> to all pages.
public string CRStatus
{
set { WorkflowSignoffStatus.Text = value; }
get { return WorkflowSignoffStatus.Text; }
}
Here is my Preliminary.aspx.cs
public partial class Preliminary : System.Web.UI.Page
public string WFLCRStatus
{
get
{ object value = HttpContext.Current.Session["CRStatus"];
return value == null ? "" : (string)value;
}
set
{ HttpContext.Current.Session["CRStatus"] = value;
}
}
protected void BtnToCCB_Click(object sender, EventArgs e)
{
WFLCRStatus = "In Review";
Master.CRStatus = "In Review";
Response.Redirect("CCB.aspx");
}
}
Sets value to the label but on navigating to next page the label is empty.
I created a property here in the plan of using it in master.cs's Form_Load event to display the status. But I don't know how to use it there. Unable to create an instance there to access this property.
Calling redirect after setting a label's value makes no sense.
Master.CRStatus = "In Review";
Response.Redirect("CCB.aspx");
When you redirect, the framework sends an HTTP Redirect to the client browser, and the current request/response cycle ends and a completely new one begins. Meaning the entire page lifecycle is loaded again, including the master page.
To make this work, update your Session, perform the redirect, then in the Page_Load of the next page check the Session to see if that value is there, and update the label accordingly.
WFLCRStatus.Status = "In Review"
Response.Redirect("CCB.aspx");
next page
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
if(!String.IsNullOrEmpty(Session["CRStatus"]))
{
Master.CRStatus = Session["CRStatus"].ToString();
}
}
}
Try setting a default value to WorkflowSignoffStatus then check if the control does return the correct value on BtnToCCB_Click.
I want to hide label, whenever something is typed in text box in aspx page.
I am trying something like this :
protected void txt_LastName_KeyPress(object sender, EventArgs e)
{
Label_msg.Visible = false;
}
protected void txt_LastName_KeyDown(object sender, EventArgs e)
{
Label_msg.Visible = false;
}
But it is not happening. Do I need to write something like this in focus event?
You need javascript
Here is an implementation using jQuery
<script>
$('#txt_LastName').focus(function() {
$('#Label_msg').hide();
});
$('#txt_LastName').blur(function() {
$('#Label_msg').show();
});
</script>
A plain vanilla javascript solution would be
<script>
document.getElementById("txt_LastName").onfocus = function() {
document.getElementById("Label_msg").style.display = 'none';
};
document.getElementById("txt_LastName").onblur = function() {
document.getElementById("Label_msg").style.display = 'inherit';
};
</script>
This one may be helpful for you. Do as following...
Firstly, Set Textbox's AutoPostBack Property to true
AutoPostBack="True"
Then, Use OnTextChanged Event
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Label1.Visible = false;
}
you can do some thing simple as below:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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 language="javascript" type="text/javascript">
function hideOnKeyPress() {
document.getElementById('lblHidden').style.display = 'none';
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtMaintCost" onkeypress="hideOnKeyPress(); return true;" runat="server"></asp:TextBox>
<asp:Label ID="lblHidden" runat="server" Text="I'll hide when you type something in the text box" />
</div>
</form>
</body>
</html>
You can't change the visibility of a layer event based server side. You have to put this into a javascript procedure.
You have to possibilities: The easy way is, to use jQuery (you need to include jQuery!):
<script type="text/javascript">
$(function() {
$('#txt_LastName').focus(function() {
$('#Label_msg').hide();
});
$('#txt_LastName').blur(function() {
$('#Label_msg').show();
});
}
</script>
Second method: do it the hard way
If you don't want to use jQuery for some reason, you have to work directly with the DOM.
You can read about it there: W3Schools DOM Methods
You may want to look into a JavaScript MVVM library, such as KnockoutJS, like this:
<p>Your value: <input data-bind="value: someValue, valueUpdate: 'afterkeydown'" /></p>
<p>You have typed: <span data-bind="text: someValue"></span></p>
// Here's my data model
var viewModel = {
someValue: ko.observable("edit me")
};
ko.applyBindings(viewModel); // This makes Knockout get to work
Here is a jsFiddle to illustrate how easy it is to achieve your desired key down functionality with JavaScript via KnockoutJS.
a simple javascript solution would be
HTML
<span id="one">text</span>
<input type="text" onkeypress="hide()" />
Javascript
var isHidden = false;
function hide(){
if(!isHidden){
isHidden = true;
document.getElementById("one").setAttribute("style","display:none");
}
}
jsbin demo
Because there is no KeyPress Event in ASP.Net forms unlike Winforms you must use JQuery short hand code (for JavaScript) to handle hiding your label when user is typing in the textbox like this example:
<script>
$(document).ready(function () {
$("#txtUserName").keypress(function () {
$("#lblUser").hide();
});
});
</script>
I am trying to create Div dynamically on the press of button click.
For that i refered this link>> http://forums.asp.net/t/1349244.aspx
and made code on server side(.cs page) as follows>>
public static int i = 0;
protected void Button1_Click(object sender, EventArgs e)
{
i++;
HtmlGenericControl newControl = new HtmlGenericControl("div");
newControl.ID = "NEWControl"+i;
newControl.InnerHtml = "This is a dynamically created HTML server control.";
PlaceHolder1.Controls.Add(newControl);
}
This code was giving me just one div each time when i press the button., I wanted to have addition of divs.
On client side using javascript also i tried>>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" OnClientClick="addDiv();" />
</div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</form>
</body>
</html>
<script type="text/javascript">
function addDiv() {
alert("Control comming in function");
var r = document.createElement('Div');
r.style.height = "20px";
r.style.width = "25px";
r.appendChild("div");
alert("Control going out of function");
}
</script>
Both of these didnt work.
What mistake am i making?
Is there any thing wrong?
Use this
public int Index
{
get
{
if(ViewState["Index"]==null)
{
ViewState["Index"]=0;
}
else
{
ViewState["Index"]=int.Parse(ViewState["Index"].ToString())+1;
}
return int.Parse(ViewState["Index"].ToString());
}
}
protected void Button1_Click(object sender, EventArgs e)
{
HtmlGenericControl newControl = new HtmlGenericControl("div");
newControl.ID = "NEWControl"+Index;
newControl.InnerHtml = "This is a dynamically created HTML server control.";
PlaceHolder1.Controls.Add(newControl);
}
It is giving you one div, cause you are adding one div.
Remember that asp.net needs you to create all dynamically added controls on very PostBack after that.
If you want two controls you have to add two to the PlaceHolder.
Just use one parent div with some ID(predefined lets say id="dvDynamic") and runat="server"
and then use it the dvDynamic.innerHTML = "<div> /* dynamic div contents */ </div>"
Its the simplest way, as if you are using html element in ASP.net use dom controls for better generation. Dynamic creation of control will require handled, interface and many things to co-ordinate with that control. As its not predefined by system. you have to create it.
SO choose the DOM element option. that is faster and better :)
I hope this will help :)
I have a set of stylesheets with different colour options. I have created a user control with a list of the stylesheet options which are setup as linkbuttons. On click I set a session variable with the path of the stylesheet I want to use, then on the master page I check this session and set the stylesheet accordingly.
The problem is that the stylesheet changes don't take effect until I refresh the page again. How can I force the stylesheet to reload instantly?
Here is my usercontrol:
<ul id="swatch">
<li>
<div class="green"></div>
<asp:LinkButton ID="lbGreen" runat="server" Text="Green" ClientIDMode="Static"
onclick="lbGreen_Click"></asp:LinkButton>
</li>
<li>
<div class="maroon"></div>
<asp:LinkButton ID="lbMaroon" runat="server" Text="Maroon" ClientIDMode="Static"
onclick="lbMaroon_Click"></asp:LinkButton>
</li>
<li>
<div class="silver"></div>
<asp:LinkButton ID="lbSilver" runat="server" Text="Silver" ClientIDMode="Static"
onclick="lbSilver_Click"></asp:LinkButton>
</li>
<li>
<div class="black"></div>
<asp:LinkButton ID="lbBlack" runat="server" Text="Black" ClientIDMode="Static"
onclick="lbBlack_Click"></asp:LinkButton>
</li>
</ul>
Here is the code behind for this control:
public partial class StylesheetPicker : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void lbGreen_Click(object sender, EventArgs e)
{
SetStylesheet("green");
}
protected void lbMaroon_Click(object sender, EventArgs e)
{
SetStylesheet("maroon");
}
protected void lbSilver_Click(object sender, EventArgs e)
{
SetStylesheet("silver");
}
protected void lbBlack_Click(object sender, EventArgs e)
{
SetStylesheet("black");
}
private void SetStylesheet(string selectedStyle)
{
switch (selectedStyle)
{
case "green":
Session["style"] = "/css/green.css";
break;
case "maroon":
Session["style"] = "/css/maroon.css";
break;
case "silver":
Session["style"] = "/css/silver.css";
break;
case "black":
Session["style"] = "/css/black.css";
break;
default:
Session["style"] = "/css/green.css";
break;
}
}
}
and then here is the code snippet I have on my master page:
if(Session["style"] != null)
{
var stylesheet = Session["style"];
<link rel="stylesheet" type="text/css" href="#stylesheet" />
}
else
{
<link rel="stylesheet" type="text/css" href="/css/green.css" />
}
It seems I have to click the linkbuttons twice to get the stylesheet to change. How can I do it so when the button is clicked it changes instantly?
Thanks
Give your stylesheet link element an id, then you should be able to change the href on it to something else. This code works in chrome, not sure about other browsers:
<link id="userStylesheet" rel="stylesheet" type="text/css" href="/css/green.css" />
Javascript to change it:
var linkTag = document.getElementById('userStylesheet');
linkTag.href = "css/maroon.css";
For the server side problem you could problem just redirect after they postback a change to it to get it to take effect on the next page load.
create a placeholder for your stylesheet in the master page, then you can set the stylesheet on the Page_Load/postback and not have to refresh the page?
in fact Adding StyleSheets Programmatically in Asp.Net seems to be what you are after.
If I remember correctly what ends up happening is that the session variable is getting set after the masterpage has already evaluated the if. The second click is just serving to reload the page one more time after the session variable is set in the first click (but to late to evaluate from the master.
These days there are better ways of doing this, but if you really want to make this approach work you are going to have to do something like force a page reload after the variable is set, or evaluate the post data earlier than the master page's render manually.
I have implemented master pages using this example How to implement a status bar in an ASP.NET application?. I have a property on my SiteMaster.cs inherited MasterPage called Environment. On my MasterPage.master I have this code:
<body>
<form id="frmMaster" runat="server">
<.. some content removed for brevity ...>
Environment: <%= this.Environment %>
</form>
</body>
What I would like to do is evaluate this.Environment and if it is "LIVE" then colour the background of this.Environment text red, and if it's "TEST" colour it yellow. How would I do this?
UPDATE I've just added this code to MasterPage.master
protected void Page_Load(object sender, EventArgs e)
{
lblEnvironment.Text = this.Environment;
if (this.Environment == "LIVE")
{
lblEnvironment.BackColor = System.Drawing.Color.Red;
}
}
The page loads, but the text does not get set, it's blank! Also the old text, that was populated is now blank too (I left the old code there for now). I also get a warning in Visual Studio:
'ASP.masterpage_master.Page_Load(object,
System.EventArgs)' hides inherited
member 'SiteMaster.Page_Load(object,
System.EventArgs)'. Use the new
keyword if hiding was intended.
UPDATE2: This is what I have in SiteMaster.cs
using System;
using System.Web.UI;
public class SiteMaster : MasterPage
{
public string StatusText { get; set; }
public string StatusTime { get; set; }
public string Environment { get; set; }
protected virtual void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (Session["status"] != null)
{
this.StatusText = Session["status"].ToString();
this.StatusTime = Session["statusTime"].ToString();
}
this.Environment = Session["environment"].ToString();
}
}
}
Instead of using the <%= syntax to print out the environment (this is using Response.Write), consider using a server control like a Literal or a Label. As you want to change the background colour, this suggests styling (CSS), so a Label would be appropriate.
(A Literal is just a text placeholder and renders no HTML, whereas a Label (usually) renders the text inside <span> tags.)
So I would change your master page markup to
Environment: <asp:Label ID="environmentLabel" runat="server" />
In the code-behind, set the Text property of environmentLabel to this.Environment. At the same time, test the value of the evironment, and set the BackColor property of the label as appropriate (or apply a CSS class).
UPDATE:
For a master page, you just need one class, which will inherit from System.Web.UI.MasterPage. If you create this in Visual Studio and call it SiteMaster, you'll get 3 files:
SiteMaster.Master (the markup)
SiteMaster.Master.cs (the code-behind)
SiteMaster.Master.designer.cs (automatically generated/updated)
In the SiteMaster.Master file, you'll want something like this:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="SiteMaster.master.cs" Inherits="WebApplication1.SiteMaster" %>
<!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:Label ID="environmentLabel" runat="server" />
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server" />
</div>
</form>
</body>
</html>
In SiteMaster.Master.cs, you'll need something like this:
using System;
namespace WebApplication1
{
public partial class SiteMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
this.environmentLabel.Text = "environment";
this.environmentLabel.BackColor = System.Drawing.Color.Red;
}
}
}
As the environment label is on the master page, any normal page (ASPX) using this master page will get the label displayed. Every time a page is loaded, the Page_Load event in SiteMaster.Master.cs will be called, and the text will be updated. You don't need to define the MasterPage class yourself, that's provided by the .NET framework.
You may want to improve this Page_Load method, either by using ViewState and therefore only setting the text if you're not doing a PostBack, or by disabling ViewState on the environmentLabel control.
Finally, you'll have one or more ASPX pages in your site, with something like this at the top of the markup:
<%# Page Title="" Language="C#" MasterPageFile="~/SiteMaster.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
something like this..
var preTag = #" <font style=""background:yellow;color:#ff0000;font-weight:600;""><b>";
var postTag = " </b></font>";
Environment: <%= ((this.Environment=="LIVE") ? (preTag + this.Environment + postTag) : this.Environment) %>
You can also move the code from Page_Load to Page_PreRender in MasterPage.master and it should work.. it was blank because MasterPage.master Page_Load overwritten the Page_Load of SiteMaster.Master thus Environment was never assigned.