I'm trying to make it so if your Session["LoggedIn"] is true, the wuc (Web User Control, which is the Navbar and is connected to the MasterPage which is connected to the page) prints a logout button.
so I have it like this:
Response.Write("<a runat='server' ID='lblLogout' class='nav-link' CausesValidation='False' OnServerClick='lblLogout_Click'>Logout</a>");
the CodeBehind function looks like this:
protected void lblLogout_Click(object sender, EventArgs e)
{
Session.RemoveAll();
Session["LoggedIn"] = false;
Session["IsAdmin"] = false;
Session["Username"] = "";
}
now, I've tried everything, if I use response.write like that, I can't click it, it just doesn't fire or do anything, if I don't use it inside Response.Write, it does work..
I even tried prinitng an asp:LinkButton instead to see if that works, but it doesn't print out anything when I use it like:
Response.Write("<asp:LinkButton class='nav-link' runat='server' ID='lblLogout' Text='Logout' CausesValidation='False' OnClick='lblLogout_Click' />");
Now the solution that I found was putting another page for logout and placing the function on PageLoad, which works, but I'm wondering if I can make it work so I can use the function from CodeBehind, instead of having to go to another page.
my working solution:
if ((bool)Session["LoggedIn"] == true)
{
Response.Write("<li class='nav-item'> <a runat='server' ID='lblLogout' class='nav-link' CausesValidation='False' href='../PagesForVisitor/wfLogout.aspx'>Logout</a></li><li><a class='navbar-brand' href='#'><img src='" + GetSource() + "' width = '30' height = '30' alt = ''/ ></a></li>");
}
(this one prints out a profile pic as well)
p.s using Bootstrap for styling, not sure if that matters, thanks a bunch..
You should use
<asp:Button id='' runat='server'>
tag
or use css to custom the button look depending on the style.
You can make it a hyperlink in the properties.
Warning: I am a novice when it comes to ASP and javascript - I'm more used to desktop apps. Web development is completely new to me.
I have inherited an ASP.net project that I need to keep up-to-date.
My current problem is that I need to display the client time in a text control (label or literal control - doesn't have to specifically be one of those, I just need to show it in text) when the user has clicked a button to 'Save'. If I do it server-side, in the 'SaveChanges' function, I get the time of where the server is.
My button is defined as below:
<asp:Button ID="Save" runat="server" Text="Save Changes" OnClick="SaveChanges"
ValidationGroup="ProjectSummaryValidationGroup"
meta:resourcekey="SaveResource1" />
And my Literal/Label is:
<asp:Label ID="SaveTime" runat="server"></asp:Label>
I have found a javascript function to calculate the client time from one of the other questions on here: (EDIT: I have updated this function so that the text value of my label is being assigned a value)
<script type="text/javascript">
function GetDate(date) {
CurTime = new Date(date);
var offset = (new Date().getTimezoneOffset() / 60) * (-1);
var utc = CurTime.getTime() + (offset * 60000 * (-1));
var serverDate = new Date(utc + (3600000 * offset));
var dateString = (serverDate.getMonth() + 1) + "/" + serverDate.getDate() + "/" +
serverDate.getFullYear() + " " + serverDate.toLocaleTimeString("en-US", { hour12: true });
document.getElementById('<%=SaveTime.ClientID%>').Text = dateString;
}
</script>
My problem is I don't know where to put this javascript function in my apsx page, or how to set the Text value of my label to the date string calculated in the function. I don't even know for sure how to 'call' this function...
So my questions are:
Where do I have to define the javascript function?
How to I 'call' this javascript function when the user clicks the 'Save' button, so that the text one my age is updated?
You can use Java Script Function like
<script type="text/javascript" language="javascript">
function javascriptFunction()
{
}
</script>
call this function
If you Used Update Panels Then You can Use in .Cs Page:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "javascriptFunction();", true);
or On Button's Click in .aspx page
<asp:Button ID="Save" runat="server" Text="Save Changes" OnClick="SaveChanges"
onClientClick="javascriptFunction();"
ValidationGroup="ProjectSummaryValidationGroup"
meta:resourcekey="SaveResource1" />
Other Wise You can Use in .cs page
ClientScript.RegisterStartupScript
(GetType(),Guid.NewGuid().ToString(), "javascriptFunction();",true);
set value of Label in javascript:
document.getElementById('<%=SaveTime.ClientID%>').value = "Your Date";
for label :
void Page_Load(object sender, EventArgs e)
{
lblMyLabel.Attributes.Add("onclick",
"javascript:alert('ALERT ALERT!!!')");
}
I'm trying to get jQuery to bind an onClick function when the document loads to my radio buttons.
ASP goes back to the database and finds all the open markers and then it sends a response to the page with the raw HTML to make a radio button and an image of the marker. What I need to do is have jQuery (or anything for that matter) bind an onClick that will signal what one is clicked so I can send that markerId back to the database to attach it to a person.
Here is a rough jsFiddle of what I've tried so far. In debugging I added alerts in the each function and I see them 3x like I should but the attr('id') comes back undefined.
This is the html that puts the radio buttons on the form
<br />
<p>Select open marker for new user:
<% getMarkers(); %>
</p>
This is the codebehind for that call
while (reader.Read())
{
if (readIndex % 3 == 0)
markerTable += "<tr>";
string markerId = reader["marker_id"].ToString();
string fileName = reader["marker_filename"].ToString();
markerTable += "<td><input type=\"radio\" name=\"openMarker\" value=\"" + markerId + "\" " +
"id=\"oMrk" + markerId + "\"><label for=\"oMrk" + markerId + "\"><img src=\"/Markers/" +
fileName + "\" /></label></input></td>";
readIndex++;
if (readIndex % 3 == 0)
markerTable += "</tr>";
}
if (readIndex % 3 != 0)
markerTable += "</tr>";
markerTable += "</table>";
}
else
markerTable = "<p>No empty markers. Please delete a user to continue.</p>";
sCon.Close();
return markerTable;
The fiddle I posted has the source pasted into it from this function.
I have two questions.
Why does this not work? It seems like it should, I am getting 3 elements from my jQuery selector statement, It's being called from $(document).ready() why are the attributes undefined?
Is there a better way to do this? I was planning on putting the value in a page variable and then sending it with an ASP button back to the server to a stored procedure to add that marker with some text from another field back to the database. I realize I could add the onClick event into the response html, but dang it I need to understand why what I'm doing isn't working.
I'm pretty new to web, so if I am way off the mark procedurally, I am open for suggestion.
LINK
$(document).ready(function () {
$('input:radio').each(function (radElem) {
var radId = $(this).attr('id');
alert(radId);
});
$('input:radio').on('click', function () {
alert('Clicked');
});
});
$(document).ready(function () {
$('input:radio').on('click', function() {
alert($(this).attr('id'));
});
});
Do you need to send the value to the server while staying on the page? (via ajax)
or do you need to post the form to another page?
It doesn't work because you are trying to bind onClick instead of
just click
The other answers have provided the jQuery for you. In the each you
just need to use this keyword
I tested this in a fiddle, it works. Others have provided similar answers, but here's the fiddle anyway: THE FIDDLE
$(document).ready(function () {
$("input:radio").each(function () {
var radId = $(this).attr('id');
alert(radId);
$(this).on('click', function () {
alert('Clicked');
});
});
});
As for a better way to do what you are trying to accomplish, I do not have a firm grasp of what you are trying to do really, sorry. It feels though, like you should be initially populating this in asp.net, but the constraints of your page may not make this possible. I can't say.
Also, go ahead and pick one of the previous answers, I just wanted to explain to you why what you had wasn't working.
I have a JavaScript MessageBox that keeps displaying when I click events in a Repeater or refresh the current page.
Here is the function:
public myFunctions()
{
}
/** Display Successs/Error Message **/
public void DisplayUserMessage(string messageType, string messageString, Label ErrorMessageLabel)
{
ErrorMessageLabel.Visible = true;
ErrorMessageLabel.Text = "<b>" + messageType.Substring(0, 1).ToUpper() + messageType.Substring(1).ToLower() + ":</b> " + messageString;
ErrorMessageLabel.CssClass = messageType.ToLower() + "_message";
}
public void HideUserMessage(Label ErrorMessageLabel)
{
ErrorMessageLabel.Visible = false;
ErrorMessageLabel.Text = "";
ErrorMessageLabel.CssClass = "";
}
Here is the jquery to make it fade out:
$(document).ready(function () {
/** Success/Error Messages **/
$('.success_message').animate({ opacity: 1.0 }, 2000).fadeOut('slow');
$('.error_message').animate({ opacity: 1.0 }, 2000).fadeOut('slow');
});
Here it is on the MasterPage:
<!-- Message Box -->
<div id="msgBox" runat="server">
<asp:Label ID="ErrorMessageLabel" CssClass="" runat="server" Visible="false"></asp:Label>
</div>
Here is the script in the code-behind when a success occurs:
Label ErrorMessageLabel = (Label)Master.FindControl("ErrorMessageLabel");
new myFunctions().DisplayUserMessage("success", "Administrator Updated!", ErrorMessageLabel);
Anyone know how I can stop it from continually showing up after I click another button or refresh the page?
Use a hidden input and set the value when success function is called. All the other times reset the value. In your document ready function check the value of the hidden element and then call the animate function.
<input id="txtHidSuccess" type="hidden" runat="server" />
In page load
txtHidSuccess.Value = "0";
In the success/error function
txtHidSuccess.Value = "1";
jQuery
$(function(){
if ($("#txtHidSuccess").val() === "1") {
/** Success/Error Messages **/
$('.success_message').animate({ opacity: 1.0 }, 2000).fadeOut('slow');
$('.error_message').animate({ opacity: 1.0 }, 2000).fadeOut('slow');
}
});
I see where you're calling DisplayUserMessage(), but not HideUserMessage(). My guess is that when you set the ErrorMessageLabel properties, they're stored in the View State persisted across postbacks.
Rather than use an ASP.NET Label control, you could try just wrapping some text with a regular div and use CSS to hide it. When the success event occurs in your app, you can use ClientScriptManager.RegisterStartupScript() to write a script to the client that shows the div. Then, your animate functions can fade out the div if it's visible.
if(IsPostBack)
new myFunctions().HideUserMessage(ErrorMessageLabel);
This worked. Thanks #Harie
I want to do a Response.Redirect("MyPage.aspx") but have it open in a new browser window. I've done this before without using the JavaScript register script method. I just can't remember how?
I just found the answer and it works :)
You need to add the following to your server side link/button:
OnClientClick="aspnetForm.target ='_blank';"
My entire button code looks something like:
<asp:LinkButton ID="myButton" runat="server" Text="Click Me!"
OnClick="myButton_Click"
OnClientClick="aspnetForm.target ='_blank';"/>
In the server side OnClick I do a Response.Redirect("MyPage.aspx"); and the page is opened in a new window.
The other part you need to add is to fix the form's target otherwise every link will open in a new window. To do so add the following in the header of your POPUP window.
<script type="text/javascript">
function fixform() {
if (opener.document.getElementById("aspnetForm").target != "_blank") return;
opener.document.getElementById("aspnetForm").target = "";
opener.document.getElementById("aspnetForm").action = opener.location.href;
}
</script>
and
<body onload="fixform()">
You can use this as extension method
public static class ResponseHelper
{
public static void Redirect(this HttpResponse response, string url, string target, string windowFeatures)
{
if ((String.IsNullOrEmpty(target) || target.Equals("_self", StringComparison.OrdinalIgnoreCase)) && String.IsNullOrEmpty(windowFeatures))
{
response.Redirect(url);
}
else
{
Page page = (Page)HttpContext.Current.Handler;
if (page == null)
{
throw new InvalidOperationException("Cannot redirect to new window outside Page context.");
}
url = page.ResolveClientUrl(url);
string script;
if (!String.IsNullOrEmpty(windowFeatures))
{
script = #"window.open(""{0}"", ""{1}"", ""{2}"");";
}
else
{
script = #"window.open(""{0}"", ""{1}"");";
}
script = String.Format(script, url, target, windowFeatures);
ScriptManager.RegisterStartupScript(page, typeof(Page), "Redirect", script, true);
}
}
}
With this you get nice override on the actual Response object
Response.Redirect(redirectURL, "_blank", "menubar=0,scrollbars=1,width=780,height=900,top=10");
Contruct your url via click event handler:
string strUrl = "/some/url/path" + myvar;
Then:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('" + strUrl + "','_blank')", true);
Because Response.Redirect is initiated on the server you can't do it using that.
If you can write directly to the Response stream you could try something like:
response.write("<script>");
response.write("window.open('page.html','_blank')");
response.write("</script>");
The fixform trick is neat, but:
You may not have access to the code
of what loads in the new window.
Even if you do, you are depending on
the fact that it always loads, error
free.
And you are depending on the fact
that the user won't click another
button before the other page gets a
chance to load and run fixform.
I would suggest doing this instead:
OnClientClick="aspnetForm.target ='_blank';setTimeout('fixform()', 500);"
And set up fixform on the same page, looking like this:
function fixform() {
document.getElementById("aspnetForm").target = '';
}
You can also use in code behind like this way
ClientScript.RegisterStartupScript(this.Page.GetType(), "",
"window.open('page.aspx','Graph','height=400,width=500');", true);
This is not possible with Response.Redirect as it happens on the server side and cannot direct your browser to take that action. What would be left in the initial window? A blank page?
popup method will give a secure question to visitor..
here is my simple solution: and working everyhere.
<script type="text/javascript">
function targetMeBlank() {
document.forms[0].target = "_blank";
}
</script>
<asp:linkbutton runat="server" ID="lnkbtn1" Text="target me to blank dude" OnClick="lnkbtn1_Click" OnClientClick="targetMeBlank();"/>
<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry"
OnClick="btnNewEntry_Click" OnClientClick="aspnetForm.target ='_blank';"/>
protected void btnNewEntry_Click(object sender, EventArgs e)
{
Response.Redirect("New.aspx");
}
Source: http://dotnetchris.wordpress.com/2008/11/04/c-aspnet-responseredirect-open-into-new-window/
If you can re-structure your code so that you do not need to postback, then you can use this code in the PreRender event of the button:
protected void MyButton_OnPreRender(object sender, EventArgs e)
{
string URL = "~/MyPage.aspx";
URL = Page.ResolveClientUrl(URL);
MyButton.OnClientClick = "window.open('" + URL + "'); return false;";
}
You can also use the following code to open new page in new tab.
<asp:Button ID="Button1" runat="server" Text="Go"
OnClientClick="window.open('yourPage.aspx');return false;"
onclick="Button3_Click" />
And just call Response.Redirect("yourPage.aspx"); behind button event.
I always use this code...
Use this code
String clientScriptName = "ButtonClickScript";
Type clientScriptType = this.GetType ();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager clientScript = Page.ClientScript;
// Check to see if the client script is already registered.
if (!clientScript.IsClientScriptBlockRegistered (clientScriptType, clientScriptName))
{
StringBuilder sb = new StringBuilder ();
sb.Append ("<script type='text/javascript'>");
sb.Append ("window.open(' " + url + "')"); //URL = where you want to redirect.
sb.Append ("</script>");
clientScript.RegisterClientScriptBlock (clientScriptType, clientScriptName, sb.ToString ());
}
Here's a jQuery version based on the answer by #takrl and #tom above. Note: no hardcoded formid (named aspnetForm above) and also does not use direct form.target references which Firefox may find problematic:
<asp:Button ID="btnSubmit" OnClientClick="openNewWin();" Text="Submit" OnClick="btn_OnClick" runat="server"/>
Then in your js file referenced on the SAME page:
function openNewWin () {
$('form').attr('target','_blank');
setTimeout('resetFormTarget()', 500);
}
function resetFormTarget(){
$('form').attr('target','');
}
I used Hyperlink instead of LinkButton and it worked just fine, it has the Target property so it solved my problem. There was the solution with Response.Write but that was messing up my layout, and the one with ScriptManager, at every refresh or back was reopening the window. So this is how I solved it:
<asp:HyperLink CssClass="hlk11" ID="hlkLink" runat="server" Text='<%# Eval("LinkText") %>' Visible='<%# !(bool)Eval("IsDocument") %>' Target="_blank" NavigateUrl='<%# Eval("WebAddress") %>'></asp:HyperLink>
You may want to use the Page.RegisterStartupScript to ensure that the javascript fires on page load.
you can open new window from asp.net code behind using ajax like I did here
http://alexandershapovalov.com/open-new-window-from-code-behind-in-aspnet-68/
protected void Page_Load(object sender, EventArgs e)
{
Calendar1.SelectionChanged += CalendarSelectionChanged;
}
private void CalendarSelectionChanged(object sender, EventArgs e)
{
DateTime selectedDate = ((Calendar) sender).SelectedDate;
string url = "HistoryRates.aspx?date="
+ HttpUtility.UrlEncode(selectedDate.ToShortDateString());
ScriptManager.RegisterClientScriptBlock(this, GetType(),
"rates" + selectedDate, "openWindow('" + url + "');", true);
}
None of the previous examples worked for me, so I decided to post my solution. In the button click events, here is the code behind.
Dim URL As String = "http://www.google/?Search=" + txtExample.Text.ToString
URL = Page.ResolveClientUrl(URL)
btnSearch.OnClientClick = "window.open('" + URL + "'); return false;"
I was having to modify someone else's response.redirect code to open in a new browser.
I used this approach, it doesn't require you to do anything on the popup (which I didn't have access to because I was redirecting to a PDF file). It also uses classes.
$(function () {
//--- setup click event for elements that use a response.redirect in code behind but should open in a new window
$(".new-window").on("click", function () {
//--- change the form's target
$("#aspnetForm").prop("target", "_blank");
//--- change the target back after the window has opened
setTimeout(function () {
$("#aspnetForm").prop("target", "");
}, 1);
});
});
To use, add the class "new-window" to any element. You do not need to add anything to the body tag. This function sets up the new window and fixes it in the same function.
I did this by putting target="_blank" in the linkbutton
<asp:LinkButton ID="btn" runat="server" CausesValidation="false" Text="Print" Visible="false" target="_blank" />
then in the codebehind pageload just set the href attribute:
btn.Attributes("href") = String.Format(ResolveUrl("~/") + "test/TestForm.aspx?formId={0}", formId)
HTML
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick = "SetTarget();" />
Javascript:
function SetTarget() {
document.forms[0].target = "_blank";}
AND codebehind:
Response.Redirect(URL);