I am new to ASP.NET (and web development in general).
For some reason, in my ASP.NET master page, the hyperlink web controls are not working.
I want them as web controls so I can change the "Login" hyperlink text to "Log out" (as well as its navigateURL) if the user session is currently logged in.
Could anyone find the problem?
Here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
<title></title>
<link href="~/Styles/default.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
<style type="text/css">
.style1
{
width: 468px;
}
</style>
</head>
<body>
<form id="Form1" runat="server">
<div id="wrapper" runat="server">
<div id="header" class="container" runat="server">
<table style="width: 100%; height: 128px;" runat="server">
<tr>
<td class="style1" runat="server">
WEBLINK
</td>
<td>
<asp:HyperLink ID="HyperLink1" runat="server">About</asp:HyperLink>
</td>
<td>
<asp:HyperLink ID="HyperLink2" runat="server"
NavigateUrl="~/InterestPages/InterestNews.aspx">Interests</asp:HyperLink>
</td>
<td>
<asp:HyperLink ID="HyperLink3" runat="server">Blogs</asp:HyperLink>
</td>
<td>
<asp:HyperLink ID="loginLink" runat="server" NavigateUrl="~/Account/Login.aspx"
ViewStateMode="Enabled">Login</asp:HyperLink>
</td>
</tr>
</table>
</div>
</div>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</form>
</body>
Here is my C# master page code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SiteMaster : System.Web.UI.MasterPage
{
private void Page_PreInit(object sender, EventArgs e)
{
if (Session["LoggedIn"] != null && (bool)Session["LoggedIn"] == true)
{
MasterPageFile = "~/LoggedIn.master";
}
else
{
MasterPageFile = "~/Site.master";
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session["LoggedIn"] != null && (bool)Session["LoggedIn"] == true)
{
loginLink.Text = "Log out";
loginLink.NavigateUrl = "";
}
else
{
loginLink.Enabled = true;
loginLink.Text = "Login";
loginLink.NavigateUrl = "~/Account/Login.aspx";
}
}
}
Why not just replace your login menu link with the asp LoginView control?
You can add an Anonymous template with your login link to point to your login page, and
a LoggedIn template with your logout link by adding the LoginStatus.
It let's you provide a welcome to the logged user.
Oh, and it also let's you get rid of all that preinit stuff and session tracking.
You can use the user identity isAuthenticated to determine if that session is logged in.
And if you want to use a different master page for your login page ... you can just create one for your login page or point it to another master page.
I also don't think your pre-init is firing.
You have empty NavigateUrl when session is not null . So please change this line loginLink.NavigateUrl = "#";
try this code
if (Session["LoggedIn"] != null && (bool)Session["LoggedIn"] == true)
{
loginLink.Text = "Log out";
loginLink.NavigateUrl = "#";
}
else
{
loginLink.Enabled = true;
loginLink.Text = "Login";
loginLink.NavigateUrl = "~/Account/Login.aspx";
}
Related
my question was that when I send the request to the web server, of course, the web server will take the request and give me a page that will be in the HTML format so I want to know when the web server will execute asp server-side controls into HTML format than in the Testing. aspx.cs file will be changed as well? it means these two lines int no1 = Convert.ToInt32(textbox1.Text);
int no2 = Convert.ToInt32(textbox2.Text);
these two lines will be converted into like this int no1=Convert.ToInt32(Response["textbox1"]);
int no1=Convert.ToInt32(Response["textbox2"]); these two lines will be converted like this or not
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Testing.aspx.cs" Inherits="login.Testing" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="background-image:url(C:\Users\Sudarshan\source\repos\login\login\Images\uWjEogFLUTBc8mSvagdiuP.jpg)">
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td>
Enter the Number 1:<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Enter the Number 2:<asp:TextBox ID="textbox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<center>
<br />
<br />
<asp:Button ID="button1" runat ="server" Text="Add" Height="38px" OnClick="Unnamed1_Click" Width="101px" /> </center>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
--------------------------------------------------------------
Testing.aspx.cs
using System;
using System.Collections.Generic;
using System. Linq;
using System. Web;
using System.Web.UI;
using System.Web. UI.WebControls;
namespace login
{
public partial class Testing: System.Web. UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed1_Click(object sender, EventArgs e)
{
int no1 = Convert.ToInt32(textbox1.Text);
int no2 = Convert.ToInt32(textbox2.Text);
int result;
result = no1 + no2;
Response.Write(result);
}
}
}
how to set or get html elements inner text or html controls value in Razor syntax.
i know how we can do this in aspx file using Runat="server" attribute like this
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title><%Response.Write(Page.Title); %></title>
<script runat="server">
protected void Button1_ServerClick(object sender, EventArgs e)
{
p1.InnerText = "Hello " + textbox1.Value; //get textbox value and set in html p tag
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="textbox1" runat="server" /><br />
<input type="button" id="btn" runat="server" value="Click Me" onserverclick="Button1_ServerClick" />
<p id="p1" runat="server">see result here</p>
</div>
</form>
</body>
</html>
Basically something like this...
View (SomeAction.cshtml):
...
<p>ViewBag.SomeValue</p>
...
Controller:
...
[HttpGet]
public ActionResult SomeAction()
{
ViewBag.SomeValue = "Hello";
return View();
}
...
However you should learn much about approach which is used to build applications using ASP.MVC. It's completely different than ASP.NET WebForms. WebForms technology uses events while ASP.MVC uses Model View Controller. You have to change your mindset.
I am working on web application.
In this application user need to login to perform some task. I have made my custom login screen. I want to make the login status of site.master to get updated as soon as user logs in but to be frank, i don't know how to do it.
The code below is taken from the login.aspx.cs. When user click login button following code will be executed. But i don't know i can i update the login status in site.master(Picture Included)
protected void Button1_Click(object sender, EventArgs e)
{
string user = username.Text;
string pass = password.Text;
Session["firstName"] = username.Text;
localhost.UserRegistration n = new localhost.UserRegistration();
if (n.checkUser(user, pass))
{
Response.Redirect("UserProfile.aspx");
}
else
{
message1.Text = "UserName or Password is Wrong. Please check your details and login again.";
}
Please Click Here to look the Picture so someone might have idea on it.
Site.Master Code
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="SystemSoftware.SiteMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form runat="server">
<div class="page">
<div class="header">
<div class="title">
<h1>
My ASP.NET Application
</h1>
</div>
<div class="loginDisplay">
<asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
<AnonymousTemplate>
[ Log In ]
</AnonymousTemplate>
<LoggedInTemplate>
Welcome <span class="bold"><asp:LoginName ID="HeadLoginName" runat="server" /></span>!
[ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/"/> ]
</LoggedInTemplate>
</asp:LoginView>
</div>
<div class="clear hideSkiplink">
<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal">
<Items>
<asp:MenuItem NavigateUrl="~/Create Account.aspx" Text="Create Account"/>
</Items>
</asp:Menu>
</div>
</div>
<div class="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server"/>
</div>
<div class="clear">
</div>
</div>
<div class="footer">
</div>
</form>
</body>
</html>
Site.Master.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SystemSoftware
{
public partial class SiteMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["firstName"] != null)
{
HeadLoginView.Visible = false;
}
else
{
HeadLoginView.Visible = true;
}
}
}
}
In you masterpage load event check for session that you are creating when user is logged in . If that session is not empty show logout link else keep that link login . In your master aspx add 2 links 1 for login one for logout.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Username"]!=null && Session["Username"]!=String.Empty)
{
lnkLogin.visible = false;
lnkLogout.visible = true;
}else{
lnkLogin.visible = true;
lnkLogout.visible = false;
}
}
you can also change the properties of controls on master page from local page also like
String a = ((LinkButton)Master.FindControl("LinkLogIn")).Text
in the same manner you can modify any other property too
A panel web control lets a developer put the panel on a page and define content that will appear inside the panel.
Is it possible to achieve similar functionality with a user control, where I define all my custom 'chrome' in the control, but am able to drop it on a page wherever I want and define the content inside on a per instance basis?
I think you are talking about a Templated User Control. Good luck!
Options:
1) Templated Controls as referred to by Uwe and Hanlet
2) jQuery UI library
3) ASP.NET 2.0 Web Parts
It's really tricky to implement no matter which way you go.
As Hanlet EscaƱo pointed out, this is complete possible to do. I'll show:
This is the user control markup:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TemplatedUserControl.ascx.cs" Inherits="Templated_User_Control.TemplatedUserControl" %>
<table border="1">
<tr>
<th>Head</th>
</tr>
<tr>
<td>
<asp:PlaceHolder ID="plContent" runat="server"></asp:PlaceHolder>
</td>
</tr>
<tr>
<td>Foot</td>
</tr>
</table>
This is the user control code:
using System;
using System.Web.UI;
namespace Templated_User_Control
{
public partial class TemplatedUserControl : System.Web.UI.UserControl
{
private ITemplate content_m = null;
[TemplateContainer(typeof(ContentContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate Content
{
get
{
return content_m;
}
set
{
content_m = value;
}
}
void Page_Init()
{
if (content_m != null)
{
ContentContainer container = new ContentContainer();
//This is the real magic. Take the contents, and put it in our ContentContainer object, then
//add the ContentContainer object as a child control of the placeholder so it renders inside the user control
content_m.InstantiateIn(container);
this.plContent.Controls.Add(container);
}
}
protected void Page_Load(object sender, EventArgs e) {}
public class ContentContainer : Control, INamingContainer {}
}
}
This is the page markup:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Templated_User_Control.Default" %>
<%# Register src="TemplatedUserControl.ascx" tagname="TemplatedUserControl" tagprefix="uc1" %>
<!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>
<uc1:TemplatedUserControl ID="TemplatedUserControl1" runat="server">
<Content>
Template user control test.<br />
<asp:Literal ID="litTest" runat="server">this is a test!</asp:Literal><br />
abc 123!
</Content>
</uc1:TemplatedUserControl>
</div>
</form>
</body>
</html>
Yes, this is completely possible.
Here is a great example where a developer overrides an existing control (I chose an article with a Panel, since you used it as an example) and still allows content within.
The article is good, but you may find the sample code even more helpful.
I've made a simple ASP.net website and everything works fine on my computer. But on my colleague's computer no postbacks are fired although he uses the same OS (Win 7) AND the same browser as I do (IE9).
I don't have any access to his computer right now which makes it kind of hard to debug. Does anybody know what could prevent postbacks on one computer although they work on a different one with the same browser?
(I also tried it on a 3rd computer with different browser and OS and it worked there too)
//update: some code
The following code is one of the pages where the problem occures.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="NewList.aspx.cs" Inherits="QAList.NewList" %>
<!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>Items</title>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
<link href="qalist.css" rel="stylesheet" type="text/css" />
<script src="lib/jquery-1.4.3.min.js" type="text/javascript"></script>
<script src="lib/jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.5.custom.css" type="text/css" media="screen" charset="utf-8" />
<style type="text/css">
input[disabled]
{
background-color:#888888;
}
.Filled
{
width: 98%;
}
.Property
{ margin-bottom: 0px;
}
.Date
{
/* this class is only used to indicate that the value is a DateTime value */
}
.PropertyTable td
{
border-bottom: 1px solid #D8D8D8;
padding:1px;
background-color:#F6F6F6;
}
.Suppler_style
{
color: #0000BB;
}
</style>
<script type="text/javascript">
$(function () {
$(".Date").datepicker({ dateFormat: "yy/mm/dd" });
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table style="width: 80%;" border="0" class="PropertyTable" cellspacing="0" cellpadding="0">
<tr>
<td style="width: 227px;">
Project Number</td>
<td>
<asp:TextBox ID="ProjectNumber" runat="server" CssClass="Property" Width="200px"></asp:TextBox>
<asp:Button ID="btApplyPnr" runat="server" Text=" apply "
onclick="btApplyPnr_Click" />
</td>
</tr>
<tr>
<td>
Contract No.</td>
<td>
<asp:DropDownList ID="ddContractNo" runat="server" AutoPostBack="True"
onselectedindexchanged="ContractNo_SelectedIndexChanged"
CssClass="Filled">
</asp:DropDownList>
<input type="hidden" class="Property" id="V_QA_PO_tp_listId" runat="server" />
<input type="hidden" class="Property" id="V_QA_PO_tp_ID" runat="server" />
<input type="hidden" class="Property" id="ContractNo" runat="server" />
</td>
</tr>
<tr>
<td>
ITP No</td>
<td>
<asp:TextBox ID="ITPNo" runat="server" CssClass="Filled Property"></asp:TextBox>
</td>
</tr>
<tr>
<td class="Suppler_style">
ITP Name</td>
<td>
<asp:TextBox ID="ITPName" runat="server" CssClass="Filled Property"></asp:TextBox>
</td>
</tr>
<tr>
<td class="Suppler_style">
Status Delivery/Finish Date</td>
<td>
<asp:TextBox ID="StatusDeliveryFinishDate" runat="server"
CssClass="Filled Property Date"></asp:TextBox>
</td>
</tr>
</table>
</form>
</body>
</html>
And the C#-Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace QAList
{
public partial class NewList : System.Web.UI.Page
{
private string current_contract = "0";
private string current_pnr;
protected void Page_Load(object sender, EventArgs e)
{
current_contract = ddContractNo.SelectedValue;
}
protected void Page_PreRender(object sender, EventArgs e)
{
//load Contract Numbers
ddContractNo.Items.Clear();
ddContractNo.Items.Add(new ListItem("-", "0"));
foreach (DataRow contract in DBAccess.Instance.getContractNumbers(current_pnr).Rows)
{
ddContractNo.Items.Add(new ListItem(contract["ProjectNumber"] + " - " + contract["ContractNo"] + " - " + contract["GoodsServicesSupplied"], contract["tp_listId"] + "_" + contract["tp_ID"]));
}
try
{
ddContractNo.SelectedValue = current_contract;
}
catch (ArgumentOutOfRangeException)
{
ddContractNo.SelectedValue = null;
applyNewContractValue();
}
}
protected void ContractNo_SelectedIndexChanged(object sender, EventArgs e)
{
applyNewContractValue();
}
private void applyNewContractValue()
{
current_contract = ddContractNo.SelectedValue;
if (!String.IsNullOrEmpty(current_contract) && current_contract != "0")
{
Guid tp_listId = new Guid(current_contract.Split('_')[0]);
int tp_ID = Convert.ToInt32(current_contract.Split('_')[1]);
DataRow row = DBAccess.Instance.getContractInfos(tp_listId, tp_ID);
if (row == null)
return;
ITPName.Text = row.IsNull("GoodsServicesSupplied") ? "" : row["GoodsServicesSupplied"].ToString();
if (!row.IsNull("PlannedDeliveryexworks"))
{
DateTime tmp = (DateTime)row["PlannedDeliveryexworks"];
StatusDeliveryFinishDate.Text = tmp.Year + "/" + fillZeros(tmp.Month, 2) + "/" + fillZeros(tmp.Day, 2);
}
}
else
{
ITPName.Text = "";
}
}
private string fillZeros(int nr, int min_length)
{
string res = nr.ToString();
while (res.Length < min_length)
res = "0" + res;
return res;
}
protected void btApplyPnr_Click(object sender, EventArgs e)
{
current_pnr = ProjectNumber.Text;
}
}
}
Check if your collegue got some script blocker installed, those can prevent postbacks since they are Javascript driven.
In case this helps someone:
I had something similar occur and it turned out that it was due to some validation controls on the page. They were for some hidden text boxes that were not actually visible and had no validation group specified. On one of the computers the errors were ignored and the postback worked, whereas on the second computer the postback failed due to validation errors. Because the text boxes were not currently visible, the problem was not immediately obvious.
Once I set up validation groups, the problem went away. I don't know why the behaviour was different on the two computers as both are running Chrome on Windows 10.