I need to detect a postback in the frontend so I can use it with JQuery to change a class on page load. How can I do this?
You can check the IsPostBack property. Eg:
<script type="text/javascript">
$(function()
{
var isPostBack = <%=Page.IsPostBack.ToString().ToLower()%>;
if (isPostBack)
{
alert("Postback");
}
});
</script>
Stolen from this post:
On the server side have this
if(IsPostBack)
{
// NOTE: the following uses an overload of RegisterClientScriptBlock()
// that will surround our string with the needed script tags
ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
}
On client side this
if(isPostBack) {
// do your thing
}
I put this variable inside the header tag of my asp.net web forms page.
<script type="text/javascript">
var isPostBack = ("true"==="<%= Page.IsPostBack ? "true" : "false" %>");
</script>
The var contains a Boolean. The comparison can probably be shortened.
Simple:
if you're using jquery it has to go after(jquery goes nuts otherwise):
$(document).ready(function(){
});
var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
Then
function whatever(){
if (isPostBack){
//Whatever you want to do
}else{
//Whatever else you want to do
}
}
I'm actually using it with jquery to show a web service status box then force a postback to refresh a ListView, so when it posts back it doesn't invoke the web service or show the status box just the updated ListView data.
$("a[href^='javascript:__doPostBack']").click(function () {
// do something
});
Related
I am using MVC 4 with java script.
Today's i have a requirement to disable to back button in all browsers, need to prevent to go-back to previous page(home page) after click on log-out button with the help of back button of browsers.
Help Me thanks.
Try this
JavaScript Code Sample
javascript code to all the pages where we need to disable the browser back button.
<script type="text/javascript">
//Disable Back Button In All Browsers.
function DisableBackButtonAllBrowsers() {
window.history.forward()
};
DisableBackButtonAllBrowsers();
window.onload = DisableBackButtonAllBrowsers;
window.onpageshow = function (evts) { if (evts.persisted) DisableBackButtonAllBrowsers(); };
window.onunload = function () { void (0) };
</script>
ActionResult code sample in mvc 4
Code for response to ActionResult for log-out in MVC 4. i.e.
/// <summary> /// Logs user out and renders login <see cref="View"/> /// </summary> /// <returns>Login <see cref="View"/></returns>
public ActionResult Logout()
{
//Disable back button In all browsers.
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
FormsAuthentication.SignOut();
return View("Login");
}
Try this, may it will help you.
Link: http://hightechnology.in/how-to-disable-browser-back-button-in-asp-net-using-javascript/
Javascript Code:
<script type = "text/javascript" >
function preventBack(){window.history.forward();}
setTimeout("preventBack()", 0);
window.onunload=function(){null};
</script>
You can use as below :
<script type="text/javascript" language="javascript">
function DisableBackButton() {
window.history.forward()
}
DisableBackButton();
window.onload = DisableBackButton;
window.onpageshow = function(evt) { if (evt.persisted) DisableBackButton() }
window.onunload = function() { void (0) }
</script>
Possible duplicate..
there is a solution mentioned befor here:
set cachebality to noCache..
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Disable browser "back" button
Disable browser's back button
Ideally you want to prevent your session history from getting populated in the first place.
location.replace(url)
From: https://developer.mozilla.org/en-US/docs/Web/API/Location/replace
The Location.replace() method replaces the current resource with the one at the provided URL. After using replace() the current page will not be saved in session History, meaning the user won't be able to use the back button to navigate to it.
If the session history is empty, the back button is disabled. If your app depends heavily on form submission, jQuery makes it easy to convert form variables to a query string for use with location.replace.
function submitForm() {
// this eliminates issues with the back button
window.location.replace('?' + jQuery.param(jQuery('form').serializeArray()));
}
sorry if my english is poor.
I've a question, i think that the problem is my poor knowledge of javascript but.. i know that you can help me about this.
i've a page with an imagebutton, i use this for delete data and i need a confirmation dialog box. Alertify is pretty, i use altertify alert in server side like this:
string myScript2 = "alertify.error('message.')";
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(),
Guid.NewGuid().ToString(), myScript2, true);
return;
and work fine!
but i don't understand how to use alertify.confirm.
for example i've used
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="../../js/alertify.min.js"></script>
<!-- include the core styles -->
<link rel="stylesheet" href="../../js/alertify.core.css" />
<!-- include a theme, can be included into the core instead of 2 separate files -->
<link rel="stylesheet" href="../../js/alertify.default.css" />
<script type="text/javascript">
$("#btElimina").on('click', function () {
alertify.confirm("This is a confirm dialog", function (e) {
if (e) {
alertify.success("You've clicked OK");
} else {
alertify.error("You've clicked Cancel");
}
});
return false;
});
</script>
but nothing to do...i can't use onclientclick because alertify is a non-blocking instead a modal windows...
can you help me to understand? not to write code for me, but, to understand and make me viable
thank you
Henry
Replace alertify.success("You've clicked OK"); with return true;
and alertify.error("You've clicked Cancel"); with return false;
Also change this:
$("#btElimina").on('click', function () {
to this:
$("#<%=btElimina.ClientID%>").on('click', return function () {
I used this and it is working:
My button is :
<asp:ImageButton ToolTip="Çıkış" ID="ImageButton1" ImageUrl="Image/Exit.png" runat="server" OnClick="btnLogout_Click" />
My script is:
<script type="text/javascript">
$("#ImageButton1").on('click', function () {
alertify.confirm("This is a confirm dialog", function (e) {
if (e) {
alertify.success("You've clicked OK");
__doPostBack("<%=ImageButton1.UniqueID%>", "");
} else {
alertify.error("You've clicked Cancel");
}
});
return false;
});
</script>
Here when i clicked "cancel" button returns false and doing nothing but when you clicked ok button i am doing postback for related button and you can write your own code in server side
protected void btnLogout_Click(object sender, EventArgs e)
{
Session.RemoveAll();
Response.Redirect("~/Login.aspx");
...
}
I can't comment on the last comment below as I don't have 50 reputation, so I'm posting an answer simply to elaborate on Ratna's answer.
As per Ratna's answer, you should use server tags to refer to ASP.Net controls (controls with runat="server") to ensure that you get the control regardless of what ASP.Net renames the control to.
So to reiterate Ratna's answer:
Instead of
$('#btElimina').on(..
use
$('#<%= btElimina.ClientID %>').on(..
to make sure that you get the correct clientside control id in your jQuery script.
I created a javascript confirm as below.
<script Type="Text/Javascript">
function CheckListBox(lvi)
{
if(lvi == "")
{
if(confirm("Are you sure?"))
{
return true;
}
else
{
return false;
}
}
}
</script>
I need to test if the ListBox.Items control is empty... I already made reference on my aspx page
<script language="javascript" type="text/javascript" src="/JS/confirm.js"></script>
I want to know how to call it on my aspx.cs page . . . So I can pass the parameter:
string oi = Listbox_Clubes.Items.Count.ToString();//Its the parameter I want to pass
See this link for how to execute javascript from code behind
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "CheckListBox(" + Listbox_Clubes.Items.Count.ToString() + ");", false);
}
Note: you must add a ScriptManager control in aspx page.
For your javascript, you can get the value without the code-behind (this assumes the script code is in the same page, in order to get the client ID):
<script>
function ClickListBox() {
if ($("#<%= Listbox_Clubes.ClientID %>").val() === null) {
if (confirm("Are you sure?")) {
return true;
}
else {
return false;
}
}
}
</script>
Similarly, you don't use javascript to validate on the server side. The code you posted will return all items in the ListBox. Here is one way to get the count of the number of selected items (I'm using .ToString() based on the OP code example):
string oi = Listbox_Clubes.Items.Cast<ListItem>().Where(i => i.Selected).Count().ToString();
However, there is no reason why you would get this value and pass it back to the client-side to do validation (what it sounds like you want to do in your post). Mainly because this involves a post-back, and client-side validation, by its nature, should occur before post-back. Also, you will still need to do server-side validation, even when you have client-side validation.
Related: in the code-behind, you can test to see if anything is selected by:
bool hasValue = Listbox_Clubes.SelectedItem != null;
The .SelectedItem returns the selected item with the lowest index in the list control. When nothing is selected, this value is null... so you know if the value isn't null, then at least one item was selected.
If you want to require that they choose at least one item, you can use a RequireFieldValidator and let that handle both validations. If you haven't done much with ASP.NET validators, that would be one good thing to read up on.
It sounds like you probably should read more about client-side validation and server-side validation and how to use them... because it seems like you are mixing them up.
The count code is a modified version of code in ASP:ListBox Get Selected Items - One Liner?
In our project we are deleting something after the user left the page. We are using window.unload event for doing this.
window.onunload = function() {
// delete something
}
We are generally using buttons, linkbuttons..etc in UpdatePanel so we hadn't needed to check Page.IsPostBack property.
Today we realized that we used some buttons out of UpdatePanel and this situation had produced some errors. After that we decided to change our method, defined a global variable (var _isPostBack = false), at the top of the our page and:
window.onunload = function() {
if (_isPostBack) {
_isPostBack = false;
return;
}
// delete something
}
Altought i set the g_isPostBack in Page_Load, g_isPostBack didn't change. I tried "RegisterClientScriptBlock", "RegisterOnSubmitStatement" and "RegisterStartupScript" methods. Register methods were called before the onunload event but _isPostBack was set after onunload event had triggered...
if (IsPostBack)
{
Control c = MyClass.GetPostBackControl(this);
bool inUpdatePanel = ControlParentForUpdatePanel(c);
if (!inUpdatePanel)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "_isPostBack = true;", true);
}
}
Is there anyone to help me?
that's the trick...
if you add onsubmit attribute to your form tag:
<form id="form1" onsubmit="return yourPostBack()">
and than write your own function:
function yourPostBack()
{
_isPostBack = true;
return true;
}
and finally in the page load:
if (IsPostBack)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "_isPostBack = false;", true);
}
with this method you can understand that it is postback or not, in window.onunload
I hope i am on the right track here,
As i understand,
the OnUnload() is ClientSide,
and therefore you don't have the server objects
what you can do... is save the value in a hidden field.
As i am used to PHP you can even embed the value in a Javascript variable
Dont know if this applys to ASP.NET:
<script language="javascript">
var MyServerVariable = "<?PHP echo MyServerVariable ?>"
if(MyServerVariable == "Blah...")
{
}
</script>
translates to
<script language="javascript">
var MyServerVariable = "VALUE"
if(MyServerVariable == "Blah...")
{
}
</script>
But same thing can be done with <asp:Label /> , i am sure...
I have written the code on
ascx script:
<script src="JScripts/jquery.alerts-1.1/jquery.alerts.js" type="text/javascript"></script>
<script>
$(function() {
$('#ImageButton1').click(function() {
jAlert('Please enter a valid Suggestion ID.', 'Case Entry');
});
});
</script>
and on
Code behind:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Window", "callAlert();", true);
the problem is alert box is automatically getting disabled after some time when page load fully
What could be the reason that the alert box is being disable after clicking on OK button and how to call the callAlert function in proper way.
If you are using Master page or pages then you won't get the Client Id of the button as you are declared it should be declared as $('#<%=ImageButton1.ClientID%>') or $('[id$=ImageButton1]') hope it will solve you problem.
$(document).ready(function(){
$('#<%=ImageButton1.ClientID%>').click(function() {
alert('Please enter a valid Suggestion ID.', 'Case Entry');
});
});
You can try to put the following line before the function
$(document).ready(function() {
This will make it:
$(document).ready(function() {
$('#ImageButton1').click(function() {
jAlert('Please enter a valid Suggestion ID.', 'Case Entry');
});
});
});
If you wait till the page is ready, the alert box won't be overwritten (I hope x)).
Also when you check that text box, check if the condition is false, then give the alert.
Is the condition not false? Build in a check to check if the condition is really true. If so? Redirect.
EDIT:
var answer = Confirm: ("This page will now redirect. Are you ready?")
if (answer)
//redirect
else
return
OK, so first it's important to understand that $(function(){... and $(document).ready(function() {... are equivalent, and nothing inside either will execute until the page is fully loaded. In other words, there's no need to use
Page.ClientScript.RegisterStartupScript(this.GetType(), "Window", "callAlert();", true);
That can be removed. Also, I see that you're probably using web forms. Be mindful that the Id attribute that will be rendered is not equal to the Id of the control attribute. In other words, if you have a runat="server" control with an Id of ImageButton1, using the syntax $('#ImageButton1') in your jQuery won't work.
Taking this into account, I've added an example below that uses selectors based on class attributes.
<script type="text/javascript">
$(function () {
$('.ImageButton1').click(function (e) {
var text = $('.TextBox1').val();
var redirect = true;
if (!text) {
redirect = confirm('Empty...are you sure?');
}
if (redirect) {
window.location.href = 'http://your-redirect-here.com';
}
});
});
</script>
<input class="TextBox1" type="text" />
<input class="ImageButton1" type="button" value="Click" />
That should get you where you want to go. Let me know if you have any questions.
var answer = Confirm: ("This page will now redirect. Are you ready?")
if (answer)
{
//redirect
} else
{
return false;
}
Put this after jAlert Box:
return false;
And call the function like this:
return callAlert();