I am using ASP.NET for a web page in order to make some server calls that involve looking up user organization information. Based on that information, we need to either hide or display a div. In the header I have a C# function that definitely runs. I have tried the following lines to hide the div.
divID.Style.Add("display","none");
and
divID.Visible = false;
In the body, I am currently using an asp:Panel that runs at server and contains the id "divID". No matter what I do, I can't get the div to hide (without manually putting the styling in). I tried putting the scripts before and after the body, and it didn't make a difference. Any suggestions on the best way to do this would be appreciated.
EDIT:
Here is the C# initiating code.
<script runat="server" language="C#">
void getUserInfo(Object sender, EventArgs ev){
The rest of the C# code is irrelevant, but the relevant line shown above is definitely being run.
The HTML portion looks something like this.
<asp:Panel runat="server" id="divID" style="width:200px; height:130px; ">
<div style="text-align:center">Test Data</div>
</asp:Panel>
C# code is always compiled and run from the server-side, and so cannot impact the state of a page once rendered unless you use postbacks or callbacks. If you want to change the visible state of a control on the client-side, you will need to use Javascript on the client side (possibly triggered by a button click) to show and hide the control.
As an example, check out the solution at the link below.
https://forums.asp.net/t/1603211.aspx?Show+hide+div+on+button+click+without+postback
<script type="text/javascript">
function ToggleDiv(Flag) {
if (Flag == "first") {
document.getElementById('dvFirstDiv').style.display = 'block';
document.getElementById('dvSecondDiv').style.display = 'none';
}
else {
document.getElementById('dvFirstDiv').style.display = 'none';
document.getElementById('dvSecondDiv').style.display = 'block';
}
}
</script>
<asp:Button ID="btn" runat="server" Text="Show First Div"
OnClientClick="ToggleDiv('first');return false;" />
<asp:Button ID="Button1" runat="server" Text="Show Second Div"
OnClientClick="ToggleDiv('second');return false;" />
<br />
<div id="dvFirstDiv" style="display: none;">
First Div
</div>
<div id="dvSecondDiv" style="display: none;">
Second Div
</div>
In the header I have a C# function that definitely runs.
If you're talking about the HTML page header - no, it definitely not running. C# code is executed only server side.
Based on your post, I'm assuming we're talking WebForms here and yo have a script block in your aspx file. While this is fine, I recommend placing the server-side code into a code behind file.
So all you need to do is to add a handler for the PreRender phase of the page life cycle and place your logic for showing/hiding the div in there.
public void Page_Prerender(object sender, EventArgs e)
{
divID.Visible = false;
' OR
'divID.Style.Add("display","none");
}
Note that setting the Visible property of a WebForms control excludes the control from rendering to the page, whilst setting display: none renders it as HTML but it isn't displayed on the page.
Try in backcode: divID.Controls.clear();
This worked for me.
Related
I have a pretty extensive Classic ASP background (using server-side javascript), and my company is finally (FINALLY) making the push towards recoding everything in ASP.Net (using C#). I have a good grasp on good programming practices in Classic ASP and I usually try to make sure I code things the "right" way. I've been reading ASP.Net tutorials and feel like I have a pretty understanding of the basics. I have good discipline about separating client side javascript into external js files, keeping styling outside of the markup in external css files, etc. So, when reading these novice tutorials I understand the concept of the code-behind pages. It makes sense to me to separate the c# code from what will ultimately become the markup for the page. Making < asp:button > objects and the code-behind rules to alter them makes perfect sense.
However, I'm having a hard time wrapping my head around how to do something simple like I would have done in Classic ASP like this:
<%
if (condition) {
%>
<input type="button" value="click me" onclick="dosomething()" />
<%
}
else {
%>
<span>You don't have permission to see the button</span>
<%
}
%>
I'm having a hard time trying to figure out how I'm supposed to fit the conditional stuff you see above into the code-behind page. If I was showing a button under both circumstances, I'd make an <asp:button> object and style it in the code-behind page accordingly - but in the example above I'm only showing the button if the condition is true, and a span block if false.
I know that you don't HAVE to put ALL the c# code in the code-behind page. I can use the <% %> tags the same way I would do in Classic ASP. But, if I do that then it seems to me that it lessens the relevance of the code-behind page. For example, I know you can use an external css stylesheet to stylize your page and at the same time use inline styles on individual tags as well. I believe this to be poor practice, however. It makes it difficult to later have to adjust the styles on that element if you don't know whether to look in the markup or in the css file to find the relevant styles affecting that element.
It seems to me that the same would hold true for your markup and code-behind pages. Is it just a necessary evil to have to mix the 2, or is there a better way to do what I'm demonstrating above?
You could have in your markup:
<asp:Button .. Visible="False" />
<asp:Label .. Text="You do not have permissions" Visible="False" />
Note the Visible property. ASP.NET web forms is build on the idea of an object model, so the button and label are objects you can work with. In the code behind, you can have:
protected void Page_Load(object sender, EventArgs e) {
.
.
if (Xcondition = true) {
Button1.visible= true;
Label2.Visible = false;
}
else {
Button1.visible= false;
Label2.Visible = true;
}
}
Is the traditional way to accomplish this. You just have to figure out where in the lifecycle you need to do this, as load may not be the best (Init or PreRender event, for instance). If you only need to do this at startup once, do if (!Page.IsPostBack) { .. } to ensure it only runs once.
I made a small example that you can basically just copy/paste and mess around with a little.
This is the aspx code:
< body>
<form id="form1" runat="server">
<div>
<asp:TextBox runat="server" ID="txtCondition"></asp:TextBox>
<asp:Button runat="server" Text="Check condition" ID="btnCheckCondition" OnClick="btnCheckCondition_Click" />
<asp:Button runat="server" Text="Click me" ID="btnSubmit" OnClick="btnSubmit_Click" Visible="false"/>
<asp:Label runat="server" ID="lblMsg"></asp:Label>
</div>
</form>
</body>
this is the code behind: (if you double click on the btnCheckCondition, the click_event method will be automatically generated in your codebehind.
protected void btnCheckCondition_Click(object sender, EventArgs e)
{
if (txtCondition.Text == "Show the button")
{
btnSubmit.Visible = true;
lblMsg.Text = "You are allowed to see the button.";
}
else
{
lblMsg.Text = "You are NOT allowed to see the button.";
}
}
This will basically check the input in the textbox txtCondition. If it is equal to "Show the button", the second button will become visible. If the text is something else, the button will not appear and a label will say that you are not allowed to see the button.
have a label and a button in the page. check the condition from code behind and based on the condition, hide or show the control. you can use visibility attribute of the controls to hide or show them. Also use asp.net controls so that you can access them from code behind.
Unless you have a good reason not to, use the Visible property. (In ASP.NET Web Forms, you're asking for trouble if you change the structure of the component tree dynamically other than using repeater controls.) What I do is:
Page.aspx
<button type='button' Visible='<%# condition %>' runat='server'>
Click Me!
</button>
<span Visible='<%# !condition %>' runat='server'>
No button for you!
</span>
Page.aspx.cs
protected void Page_Load() {
if (!IsPostBack) DataBind(); // evaluates <%# ... %> expressions
}
(My preference is to make controls to "pull" data from code-behind instead of pushing it there, and use anonymous and plain HTML controls over their heavier equivalents when possible.) Any way of setting Visible before the page renders will work though.
First to help you with the easy way, to been able the condition to been recognized you need to define it and make it public on code behind. For example:
<%if (condition) {%>
<input type="button" value="click me" onclick="dosomething()" />
<%}else { %>
<span>You don't have permission to see the button</span>
<% } %>
and on code behind
public partial class OnePage : System.Web.UI.Page
{
public bool condition = false;
protected void Page_Load(object sender, EventArgs e)
{
// here change the condition
}
}
Second case with function call
<%if (fCheckAuth()) {%>
<input type="button" value="click me" onclick="dosomething()" />
<%}else { %>
<span>You don't have permission to see the button</span>
<% } %>
and on code behind
public partial class OnePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public bool fCheckAuth()
{
// return your evaluate
return false;
}
}
More asp.net form style
Now, working with the new asp.net (compared with the classic asp) you can also do that (and similar to that).
<asp:Panel runat="server" ID="pnlShowA">
<input type="button" value="click me" onclick="dosomething()" />
</asp:Panel>
<asp:Panel runat="server" ID="pnlShowB">
<span>You don't have permission to see the button</span>
</asp:Panel>
Use one asp:Panel to warp your full content, and on code behind you open it and close it.
public partial class OnePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (condition)
{
pnlShowA.Visible = true;
pnlShowB.Visible = false;
}
else
{
pnlShowA.Visible = false;
pnlShowB.Visible = true;
}
}
}
While the question is not about using ASP.NET Web Forms versus ASP.Net MVC. I felt compelled to point out that it may be more beneficial going with ASP.NET MVC rather than ASP.NET Web Forms in your scenario.
I say this because Classic ASP and ASP.NET MVC inline style is similar. In most cases you could probably convert ASP (<% %>) to Razor(a different flavor of in-lining server-side code with HTML) with little modification to the underlining logic. I don't know about you but the less code I have to write the better. For example, your above code would convert to the following Razor syntax:
#if (condition) {
<input type="button" value="click me" onclick="dosomething()" />
}
else {
<span>You don't have permission to see the button</span>
}
To answer your question, I would disable the button on the server-side. Have a disabled on the client. In the case the button is disabled, enable the Label with the appropriate text.
//Code-behind
bool correctPermission = true;
submit.Enabled = correctPermission;
noPermissionMessage.Enabled = !correctPermission;
//Client Code
<asp:Button ID="submit" runat="server" Text="Click Me" />
<asp:Label ID="noPermissionMessage" runat="server" Text="You don't have permission to see the button" Enabled="false" />
I want to make my div block draggable and it works but if I use the runat="server" Attribute for my div block that I can use the visible="false" Attribute than I don't can use the draggable.
Here my Code:
<script>
$(function () {
$("#draggablebox").draggable();
});
</script>
<div class="create_box" id="draggablebox" runat="server" visible="false">
...
</div>
What can I do this in ASP.Net?
If you use runat="server" visible="false", then that's a server-side attribute, and the element won't get sent to the client at all. Try using style="display: none;" instead -- this renders the div to the client but makes it hidden.
Note that runat="server" doesn't do anything by itself. <div runat="server"></div> sends the same thing back to the client as <div></div>. It's once you start adding server attributes along with runat="server" that ASP.Net starts modifying what gets rendered (including rendering nothing at all in the case of visible="false").
Although display:none doesn't show the element in the browser, it still outputs the HTML to the browser and relies on browser rendering to choose whether to show the element. This can cause the element to 'flicker' on screen if there's a delay between the page being loaded and the CSS being applied.
In answer to the original question, how can you apply draggable to the element if you're using runat...
Option 1:
You can set draggable server-side:
draggable.Attributes["draggable"] = "true"
This will output (from your example):
<div class="create_box" id="draggablebox" runat="server" visible="false" draggable="true">
...
</div>
Making the element draggable in HTML5 - the same as the jQuery option is doing.
Option 2:
Set through jQuery using a different selector.
You're currently selecting based on the ID, but as your control is a server-side control, it's ID as you've set, isn't what it output to the browser - the ID has become it's server-side control ID.
You could give your control a CSS class and use this to select your element instead:
<script>
$(function () {
$(".draggablebox").draggable();
});
</script>
<div class="create_box" id="draggablebox" class="draggablebox" runat="server" visible="false">
...
</div>
Option 3: Specify the correct ID in the client-side script
In the ASPX page you can modify the output javascript to use the correct 'ClientID'. See below:
<script>
$(function () {
$('<%= draggablebox.ClientID %>').draggable();
});
</script>
<div class="create_box" id="draggablebox" class="draggablebox" runat="server" visible="false">
...
</div>
I hope this helps!
Kurt
I have an asp wizard on my page with three steps.
<asp:Wizard ID="wizardBestellen" runat="server" ActiveStepIndex="0" DisplaySideBar="False" onfinishbuttonclick="wizard_NextButtonClick" onnextbuttonclick="wizard_NextButtonClick" onpreviousbuttonclick="wizard_PreviousButtonClick">
<StartNavigationTemplate></StartNavigationTemplate>
<StepNavigationTemplate></StepNavigationTemplate>
<FinishNavigationTemplate></FinishNavigationTemplate>
<WizardSteps>
<asp:WizardStep runat="server" ID="step1" StepType="Start">
<uc1:control ID="uc1" runat="server" />
</asp:WizardStep>
<asp:WizardStep runat="server"ID="step2" StepType="Step">
<uc2:control ID="uc2" runat="server" />
</asp:WizardStep>
<asp:WizardStep ID="step3" runat="server" StepType="Finish">
<uc3:control ID="uc3" runat="server" />
</asp:WizardStep>
</WizardSteps>
</asp:Wizard>
Now every control has a next and a previous button which after the click validates your data and sends you to the next step. The buttons all look like:
<asp:LinkButton ID="bntPrevious" runat="server" CommandName="MovePrevious" CssClass="buttonOrange" CausesValidation="false"><span>Previous</span></asp:LinkButton>
<asp:LinkButton ID="btnNext" runat="server" CommandName="MoveNext" CssClass="buttonOrange" CausesValidation="true"><span>Next</span></asp:LinkButton>
So far it all works perfectly..
Now i wanted to disable the buttons after clicking on it and show a div with a loader image. So i created a div named divLoader and a javascript function which hides the div the buttons are in and shows the div with the loader.
function ToggleDiv(divButton, divLabel)
{
if (divButton.style.display == 'block')
{
divButton.style.display = 'none';
divLabel.style.display = 'block';
}
else
{
divButton.style.display = 'block';
divLabel.style.display = 'none';
}
}
But i can't get this to work. The ToggleDiv function works great in another situation, so thats not the problem.
I've tried calling the function from the OnClick attribute in the linkbutton but this gave me an error. I tried the OnClientClick, but this didn't work and i also tried setting the onclick attribute in the code behind, this also was a dead end.
Can anybody explain to me what i am doing wrong or is there another way to prevent users clicking the button twice?
Sounds like you're not getting the binding to work.
The first thing I would do is check the emitted control IDs by doing a view-source. Some implementation of the .NET framework add extra fluff to these control IDs, so can't guarantee that it will be the same as appears on the form.
Next, I would try some JavaScript late binding. If you have a JavaScript file, put it there. If not create one or add a JavaScript block to the foot of your form (create a new file for preference).
All this would be much easier with a JAvaScript lbrary such as jQuery, but for the moment lets assume you don't have one.
Add a window onload event handler
window.onload = function(){
//code to go here
}
Now add the click binding for your button:
window.onload = function(){
document.getElementById("***YOUR BUTTON ID***").onclick = function(){
ToggleDiv(this, document.getElementById("***YOUR LABEL ID***"));
}
}
I said this would be a little easer with jQuery, well, this is the equivalent implementation:
$(document).ready(function(){
$("#***YOUR BUTTON ID***").click(function(){
$(this).toggle();
$("#***YOUR LABEL ID***")).toggle();
});
});
The above sample removes the need for your ToggleDiv function entirely.
To make sure that an event handler is written properly, I generally have Visual Studio generate the event for me. However, I can't find a way to do this with a div and I've tried typing it out myself to no avail. Is this even possible without writing any javascript? (I saw similar questions, but couldn't seem to find anything that fit my needs).
Edit: Basically I have a logoff div disguised to the user as a button. When they click it, I want the following to happen:
protected void LogOff_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Session.Abandon();
//This will clear the authentication cookie
HttpCookie myHttpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, "");
myHttpCookie.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(myHttpCookie);
//This will clear the session cookie (not required for my application but applying to be safe)
HttpCookie myHttpCookie2 = new HttpCookie("ASP.NET_SessionId", "");
myHttpCookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(myHttpCookie2);
FormsAuthentication.RedirectToLoginPage();
}
Here's where I call this event:
<span class="MenuItem" runat="server" onclick="LogOff_Click">Log Off</span>
Your LogOff_Click is fine. However, you need to modify your markup. Apply the onserverclick event to the <a> tag instead of <span>. In your case, try the following:
<span class="MenuItem">Log Off</span>
Description
The div element supports the javascript event onclick so you can do it.
You can check if a html element supports a given event by looking on w3c shools tag definition.
It is not clear to me what you exactly mean. You can do many things using javascript on the client side. onclick is javascript but you can do things like redirects using the serverside (Postback on ASP.NET Webforms) too. Things you do with javascript are, without doing ajax, not noticeable by the server, cause javascript get handled by the browser.
Check out my sample and this jsFiddle Demonstration
Sample for the <div> tag
Html
<div onclick="alert('hello');">hello world</div>
More Information
jsFiddle Demonstration
w3c shools tag definition
If you wanted to stay in ASP.NET, you could use a Panel control and do something like this:
Markup
<body>
<form id="form1" runat="server">
<div>
<asp:Panel runat="server" ID="pan1">click here</asp:Panel>
</div>
</form>
</body>
Code Behind
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
pan1.Attributes.Add("onclick", "javascript:alert('here');return false;");
}
}
You're still writing JavaScript, but you're staying with the ASP.NET controls and the ASP.NET way of setting client-side events.
I actually prefer the method of dknaack and Silvertiger -- put the event in the client side code (preferably a javascript file instead of inline).
Standard DOM and CSS will allow this
<div style="cursor:hand;" onclick="this.document.location.href ='http://www.google.com';">
My content
</div>
should do the trick
Not sure what exactly you intend to do. When the onclick event is triggered, you would need a handler to be called, when the event is triggered. This is done via Javascript.
You can do a form submit in the JavaScript, or trigger an Ajax callback in the Javascript, to interact with your .NET application.
Answering the original question, onclick event can be triggered via <div> tag. Make sure you test against Internet Explorer 7/8 (compatibility mode) as not all events work in IE 7/8. It should be okay in Firefox, Chrome and IE9. Save this in a file and experiment.
<html>
<head>
<script type="text/javascript">
function JSFn()
{
//you can use the div ID if needed: var id = document.getElementById('div_id');
alert("JSFn was called");
//Can do form submit or Ajax callback to interact with .NET app
}
</script>
</head>
<body>
<div>
<a id="anchor1" href="javascript:JSFn();">Make a clickable link here, you can use onclick and href='#' </a>
</div>
<div id="div_id2" onclick="JSFn()">Just click here </div>
</body>
</html>
I was wondering if it is possible to have a modalpopup show up on page load, saying that the page is loading. I have a page that gets a lot of data from an external source which means it takes a bit before any of the controls are actually filled.
I would like to have a popup or something similar that tells the user the page is loading.
I tried this:
<ajax:ModalPopupExtender ID="mpeLoader" runat="server" TargetControlID="btnLoader"
PopupControlID="pnlLoading" BackgroundCssClass="modalBackground" />
<asp:Panel ID="pnlLoading" runat="server" Width="100px" Style="display: none;">
<div class="detailspopup">
<table>
<tr>
<td><asp:Image ID="imgLoader" runat="server" ImageUrl="~/App_Themes/Main/img/loading.gif" /></td>
</tr>
<tr>
<td>Loading...</td>
</tr>
</table>
</div>
</asp:Panel>
with a dummy button btnLoader to allow me to access the show and hide from code behind. I've been toying with the .show method in the page lifecycle but I can't seem to find a way to have the poopup show when the page is loading (and disappear when loading is done). This would also be needed upon filtering the data, thus getting new data based on filter data.
Hard to say what the best solution is without more information, but one possible way to go is to make the first page just act as a "loader" containing the dialog and some javascript that will load the actual page with ajax.
Like I wrote before it depends very much on what you are trying to accomplish :-) !
But one way to do it with jQuery, if the page you are trying to load is very simple like a list without any state / postback controls is to create a "Loader"-page like the code belov and use the UrlToLoad query param for what page to load dynamically.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function()
{
$("form").load("<%= this.Request["UrlToLoad"] %> form");
});
</script>
</head>
<body>
<form runat="server">
Loading...
</form>
</body>
Have you considered using jQuery? There are some excellent modal dialog plugins available. I've used Eric Martin's SimpleModal extensively in the past, and have been very happy with it. It has hooks for callbacks both before and after displaying the dialog, so you could perform any checks you need to using functions.
Using the jQuery route - you could have a div that surrounds all the content that is still loading, and have is dimmed out/disabled with a modal dialog showing your 'page loading' message. Then you could make use of the $document.ready() functionality in jQuery to determine when the page is done loading. At this point, you could remove the dialog and fade the page in.
What I did is make a PreLoader.aspx page that will "hold" untill the page we want is loaded:
<script type="text/javascript" language="javascript">
window.onload=function()
{
$get("ctl00_ContentPlaceHolder1_btnNav",document).click();
setTimeout('document.images["Loader"].src="App_Themes/Main/img/loading.gif"', 200);
}
</script>
the button actually makes the transfer
<asp:Label ID="lblLoading" runat="server" Text="Loading the requested page. Please wait ..." />
<asp:Button ID="btnNav" Style="display: none;" runat="server" OnClick="NavTo" />
protected void NavTo(object sender, EventArgs e)
{
Response.Redirect(Request.QueryString["url"].ToString());
}
I like this as it can be reused for every heavy data page ...