Changing ContentPlaceHolder's content dynamically - c#

I have an index page as a content page and at the top of it i have a content place holder like this.
<asp:Content ID="Content3" ContentPlaceHolderID="logProcessHolder" runat="server">
<p class="header-link">login or create an account</p>
</asp:Content>
I want to change its content when users login. After login i want to put user name instead of these links. I have my login method already, just want to know how can i make this without using an another content page ? or is it a logical solution for me ? Should i use an another content page as a home page ?

I would wrap your options in asp:Panels or use the LoginView control as epaezr has done
<asp:Content ID="Content3" ContentPlaceHolderID="logProcessHolder" runat="server">
<asp:Panel ID="pnlAnonymous" runat="server">
<p class="header-link">login or create an account</p>
</asp:Panel>
<asp:Panel ID="pnlVerified" runat="server">
<asp:Literal ID="litUserName" runat="server" />
</asp:Panel>
</asp:Content>
Then in your code behind
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
pnlAnonymous.Visible = false;
pnlVerified.Visible = true;
litUserName.Text = Context.User.Identity.Name;
}
else
{
pnlAnonymous.Visible = true;
pnlVerified.Visible = false;
}
}
You don't have to use panels. You could also HTML elements and access them in the code-behind by giving them an ID and a runat="server" attribute. E.g: <p ID="loginLinks" runat="server" class="header-link">...etc...</p> where you could change the visibility with loginLinks.Visible

You can use the integrated login controls on your code, place them on the contentplaceholder and customize to show the users name...
So you place a asp:LoginView, and on its AnonymousTemplate you can place a asp:Login control and customize it, and on the LoggedInTemplate you can place the login name, a logout link, change password, etc.
Here's an example:
<asp:LoginView ID="LoginView1" runat="server">
<AnonymousTemplate>
<asp:Login ID="Login1" runat="server"></asp:Login>
</AnonymousTemplate>
<LoggedInTemplate>
<asp:LoginName ID="LoginName1" runat="server" /> | <asp:LoginStatus ID="LoginStatus1" runat="server" LogoutAction="RedirectToLoginPage" LogoutText="End session" />
</LoggedInTemplate>
</asp:LoginView>
That code should be place right inside your ContentPlaceHolder
Hope this is useful!!

there are some ways around your question depends on your login method,
if your are using ASP.NET Forms Authentication then you could display your username just like below:
<%: Context.User.Identity.Name %>
and if you wanna have those links if user is not authenticated then you could have something like this inside your current content placeholder:
<asp:Content ID="Content3" ContentPlaceHolderID="logProcessHolder" runat="server"> > <p class="header-link">
<% if(Context.User.Identity.IsAuthenticated){ %>
<div><%: Context.User.Identity.Name %></div>
logout
<%} else { %>
login or
create an account
<%} %>
</p>
</asp:Content>
alternatively if you have your own method of authentication instead of Context.User.Identity.IsAuthenticated you could check your user's authentication from the database and pass it through a property from your code behind.

Related

How can I contain the size of my literal control?

I'm working on an ASP.NET site and I'm using HttpGetRequest & HttpGetResponse to place the contents of https://news.google.com/news into a literal control on one of my pages.
The problem is that the stream is covering the entire page. I can't manage to control the size with a div or container. So the stream from the literal is covering a label that is above it (in its own div) and a menu that's inherited from SiteMaster.Master.
How can I keep the menu and label above the literal control?
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
HttpWebRequest googRequest = (HttpWebRequest)HttpWebRequest.Create("https://news.google.com/news");
HttpWebResponse resp = (HttpWebResponse)googRequest.GetResponse();
string googNews = new System.IO.StreamReader(resp.GetResponseStream()).ReadToEnd();
Literal1.Text = googNews;
Label1.Text = DateTime.Now.ToLongTimeString();
}
ASP:
<%# Page Title="" Language="C#" MasterPageFile="~/SiteMaster.Master" AutoEventWireup="true" CodeBehind="Literally.aspx.cs" Inherits="DNut.Literally" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<p>
<asp:Label ID="Label1" runat="server" Font-Names="Arial" Font-Size="Larger" Font-Italic="true"></asp:Label>
</p>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
<div>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
</asp:Content>
The content, based on how you are receiving it, will likely include an html tag, head tag and body tag. This isn't valid markup to inject into the middle of an existing html document. The typical way to include a whole page like this in another html document is via an iframe tag.
Iframe's are frowned on a bit in the web dev world and not used alot but in this case it's its a good fit for what you are trying to do. It's also helps protect your site against Cross-site scripting (XSS) attacks (verses trying to inject markup into a div via literal tag.
With an iframe tag you set the 'src' attribute to the url you want to display and you won't need the literal or the related c# code to set it.
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
<iframe src='https://news.google.com/news'></iframe>
</asp:Content>
You can style up the iframe to have a desirable height and width.

How to set visibility of a control within an UpdatePanel that uses an UpdateProgress control?

I have an update panel on a page which contains nested Panels. It has a Panel with a small form (like a log-in form) and a button. When the button is clicked, a few conditions are checked, and if passed, the first Panel is hidden and the second Panel with a larger form is displayed.
Because the larger form can take some time to load (it pulls data from other sources), the small form panel contains an UpdateProgress control.
All of this works fine.
Then I added a nested Panel within the login form Panel, placed under the UpdateProgress that will display a meaningful error message, such as if the login code is incorrect. This displays as expected. However, if the user then corrects their information and clicks the button again, the UpdateProgress displays properly, but the error message remains visible, even though I try to set it to Visible = false in code-behind.
This page does not use a master page.
Debugging shows that the Visible property does get set to false, although it still displays in the browser.
ASPX code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="custom_Default" %>
<!DOCTYPE html>
<html lang="en">
<head runat="server">
<!-- meta and link tags -->
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<!-- h1 and all that -->
<asp:ScriptManager ID="scriptManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="pnlUpdate" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlLogin" runat="server">
<!-- label and text field -->
<asp:Button ID="btnBegin" runat="server" OnClick="btnBegin_Click" />
<asp:UpdateProgress ID="updProgress" runat="server" AssociatedUpdatePanelID="pnlUpdate">
<ProgressTemplate>
<p>Loading, please wait... </p>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:Panel ID="pnlMessage" runat="server" Visible="false">
<asp:Literal ID="ltlMessage" runat="server" />
</asp:Panel>
</asp:Panel>
<asp:Panel ID="pnlMainForm" runat="server" Visible="false">
</asp:Panel>
<asp:Panel ID="pnlConfirmation" runat="server" Visible="false">
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
<!-- javascript - jquery and bootstrap -->
</body>
</html>
Code Behind (I've tried setting visible to false in the Page_Load, in the pnlUpdate_Load event, and in the btnBegin_Click event - but that error message will not go away.
protected void btnBegin_Click(object sender, EventArgs e)
{
pnlMessage.Visible = false;
Page.Validate();
if (Page.IsValid)
{
// check some conditions. if fails:
ltlMessage.Text = "Reason for failure";
pnlMessage.Visible = true; // works
}
}
I have tried removing the Visible="false" from the pnlMessage on the ASPX page and placing it in the code behind in Page_Load but I still can't hide it after the message has already been displayed.
How can I hide the pnlMessage Panel after the btnBegin is clicked the second time?
I managed to find the solution to this. Apparently there isn't a way to do it in .NET - it has to be done in JavaScript.
Here is the code I used to accomplish this.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(initializeRequest);
prm.add_endRequest(endRequest);
var _postBackElement;
function initializeRequest(sender, e) {
if (prm.get_isInAsyncPostBack()) {
e.set_cancel(true);
}
$get('pnlMessage').style.display = 'none';
}
function endRequest(sender, e) {
$get('pnlMessage').style.display = 'block';
}
</script>

UserControl in asp .net is not working?

I have created a two usercontrols in asp.net and one webform . Now i want these two usercontrols to show in form in webform but it say that there must be one head with runat="server"
this is webform where i am using UserControl!
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Light.master" CodeBehind="AdministrationPage.aspx.cs" Inherits="DXApplication5.AdministrationPage" %>
<%# Register src="~/AdminPage/AssignmentTab.ascx" tagname="AssignmentUC" tagprefix="uc1" %>
<asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server">
<table border="0">
<tr>
<td>
<div class="accountHeader">
<uc1:AssignmentUC ID="CalendarUserControl1" runat="server" />
</div>
</td>
</tr>
</table>
</asp:Content>
This is UserControl below:
<%# Control Language="C#" ClassName="AssignmentUC" AutoEventWireup="true" CodeBehind="AssignmentTab.ascx.cs" Inherits="DXApplication5.AdminPage.AssignmentTab" %>
I would add a single form to your masterpage, this may be the cause of your error.
I would also remove all other form server controls from your user controls and pages.
Try these steps:
Go to Light.master master page file and make sure that this is in there somewhere <form id="form1" runat="server"> and a closing tag, the id may be different.
Go to the following files AssignmentTab.ascx and AdministrationPage.aspx and remove any <form id="form1" runat="server"> and closing tags </form>
Check user control code if it contains a head element. Also check all dependencies to see if there are head elements present in them.
I think you have use <form id="formID" runat="server"> in both of your page and user Control .
Just remove runat="server" from your user Control Form tag .
Make sure you have in your user control cs file:
public partial class WebUserControl1 : System.Web.UI.UserControl
In ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebUserControl1" %>
In aspx parent:
<%# Register Src="WebUserControl1.ascx" TagPrefix="uc" TagName="WebUserControl1 " %>
<uc:WebUserControl1 runat="server" ID="mycontrol" />

How to hide/show a control using AJAX (AjaxControlToolkit) and C#

I know this must sound really basic but I'm really stumped here. What I'm trying to do is to show a Hyperlink once a process has completed. And this process is the AsyncFileUpload. In the ASPX page, I want to create an but have it hidden on the initial page load. If I set the Style="display: none;" seems to work but after the file upload, nothing I do, will make the control visible again. When the file is uploaded, it calls a function called FileUploadComplete. It's in here that no matter what I do, the Hyperlink won't display.
Any help is greatly appreciated :)
Thank you,
dave
Here is the ASPX Code (with recently added javascript)
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="OptionsPlaceHolder" runat="server">
<script language="javascript" type="text/javascript">
function ShowLink() {
$("#openFile").show();
}
</script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolderBody" runat="server">
<asp:UpdatePanel ID="updImportFile" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="pageHeader">
<asp:Literal runat="server" ID="pageTitle" Text="<%$ Resources:Resources, ImportFile %>" />
</div>
<ajaxToolkit:AsyncFileUpload ID="FileUpload1" runat="server" Width="600px"
UploaderStyle="Traditional" OnUploadedComplete="FileUploadComplete" ThrobberID="throbber"
CompleteBackColor="#E9F2FD" OnClientUploadComplete="ShowLink" />
<asp:Image runat="server" ID="throbber" ImageUrl="images/loading.gif" />
<br />
<asp:Hyperlink runat="server" ID="openFile" NavigateUrl="~/OpenFile.aspx" Text="Open"
style="display:none;"/>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
And here is the code behind:
protected void FileUploadComplete(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string importName = Server.MapPath(#"Uploads\") + FileUpload1.FileName;
FileUpload1.SaveAs(importName);
// Import the JSA
JSA jsa = new JSA();
jsa.Import(importName);
// Show the Hyperlink
ShowLink();
}
}
private void ShowLink()
{
openFile.Attributes["Style"] = string.Empty;
}
I didn't include the master page code. It has the ToolkitScriptManager in it.
Are you trying to show on client-side or server-side? Is the link a client-side, or server-side object? Javascript would be the standard way.
If the control is a client-side object:
document.getElementById("hyperlink_name").style.display = "block";
Or if it is a server-side object:
document.getElementById("<%= hyperlink_name.ClientID %>").style.display = "block";
I would recommend getting jQuery and using the following though:
$('#hyperlink_name').show();
Or you can use an ASP.Net Link Button and do it server-side:
linkButton.Visible = true;
It would be more helpful if you would post some of the code you have tried already so that we can get a better idea of where you are.
{first answer deleted}
[EDIT :I didn't catch that you are using AsyncFileUpload when I first read the question]
Using AsyncFileUpload inside an update panel the server is being accessed via a partial postback, as a result other controls (the hyperlink) cannot be affected on the server. This will require that you make use of javascript (or preferably jquery) to make the change on the client.
You can do it on OnClientUploadComplete function, but you have to reference the hyperlink like this: <%= hyperLink.ClientID %>.style.display = 'block';
Another more asp.net way is to use update panels. Put the hyperlink into an UpdatePanel and set a trigger on the UpdatePanel when the file is uploaded. then change the visibility on the server at UploadedComplete event.

I am having an issue with ASP .NET user controls

I have an issue currently that I can't resolve. I have a user control called "Dashboard" which then has the following markup, containing several subcontrols.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Dashboard.ascx.cs" Inherits="BlueSEQ.Controls.Dashboard.Dashboard" %>
<%# Register src="Administrator.ascx" tagname="Administrator" tagprefix="uc1" %>
<%# Register src="Provider.ascx" tagname="Provider" tagprefix="uc2" %>
<%# Register src="User.ascx" tagname="User" tagprefix="uc3" %>
<% if (isAdministrator)
{ %>
<uc1:Administrator ID="Administrator1" runat="server" />
<% }
else if (isProvider)
{ %>
<uc2:Provider ID="Provider1" runat="server" />
<% }
else
{ %>
<uc3:User ID="User1" runat="server" />
<% } %>
As you can see, I want it to display some controls or other controls depending on some conditions. However, all of these controls' "Load" event get triggered, even if they are not used.
How can I prevent this?
If you can help it, try to avoid having conditional logic in your markup. It could make the views somewhat more difficult to understand for designers (if you're working with designers) and more difficult to find and refactor this code in the future.
You should also take a look at ASP.NET MVC: Avoiding Tag Soup. Although it's ASP.NET MVC, it's still a good example of how adding logic to your views can quickly make them very difficult and unpleasant to maintain (initial example).
You could use the technique described here: How to: Add Controls to an ASP.NET Web Page Programmatically.
Your markup would look something like this.
<asp:PlaceHolder id="MyPlaceholder" />
and your codebehind would have something along the lines of
private void InitSection()
{
Control c;
if( isAdministrator )
c = Page.LoadControl("~\Administrator.ascx")
else if( isProvider )
c = Page.LoadControl("~\Provider.ascx")
else
c = Page.LoadControl("~\User.ascx");
MyPlaceholder.Controlls.Add(c);
}
The ideal way to do this is to set up asp.net role provider and use a LoginView control, something along the lines of the code below. LoginView only loads the appropriate content.
<asp:LoginView runat="server">
<AnonymousTemplate>
<uc1:User ID="User" runat="server" />
</AnonymousTemplate>
<RoleGroups>
<asp:RoleGroup Roles="Administrator">
<ContentTemplate>
<uc1:Administrator ID="Administrator1" runat="server" />
</ContentTemplate>
</asp:RoleGroup>
<asp:RoleGroup Roles="Provider">
<ContentTemplate>
<uc1:Provider ID="Provider" runat="server" />
</ContentTemplate>
</asp:RoleGroup>
</RoleGroups>
</asp:LoginView>
You have to Load the control on a specific condition instead, so try to set visible/invisible with the usercontrol, that's a much better approach
<% if (isAdministrator)
{ %>
Page.LoadControl(("~\Administrator1.ascx");
<% }
How about using a MultiView control?
MultiView on MSDN

Categories

Resources