Is it possible to create a (yes/no) javascript messagebox from code-behind, and also retrieve the return values?
I would like to set the content of a session object based on the client Yes/No.
The idea is to use this approach for redirecting iphone clients from my default web page.
"Do you want to go the iphone version of this site?"
--YES Redirect to "iphone" default page, and set a session object to avoid asking this question again if default page is requested again
within the lifespan of the session object.
--NO Set a session object to avoid asking this question again if default page is requested again within the lifespan of the session
object.
Just display the message and set an appropiate cookie. Then make your server-side react to the cookie and render the selected version of the site.
http://www.htmlite.com/JS006.php - Javascript Confirm popup
http://www.w3schools.com/js/js_cookies.asp - Javascript cookies
In Code behind on FormLoad or wherever it best suits your needs, you would just have to set your button's OnClientClick as follows:
button.OnClientClick = "IphoneVersion()";
In Markup create a function in javascript as follows:
function IphoneVersion() {
if (confirm('Do you want to go the iphone version of this site?')) {
//set hidden value here }
else { //don't set hidden value }
}
You can set your Hidden control value to yes/no text and refer to it behind code or you can redirect in the function itself.
That will do it!
Or you could stash the value in a hidden field and read it on the server side.
** EDIT **
OP Comment:
I would like to set the content of a session object based on the client Yes/No.
Either way you look at it, if he wants to set this value in session, he has to go back to the server.
Try something like this:
confirmSomething = function(){
__doPostBack("<%=Button1.ClientID%>", confirm("Are you sure?"));
}
<asp:Button ID="Button1" runat="server" OnClientClick="confirmSomething();" />
Code-behind:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
bool conf = bool.Parse(eventArgument);
}
Related
I follow below code :
function My_Function() {
var x;
if (confirm("Exit?") == true) {
x = "Ok";
window.location.href = '#Url.Action("Login", "Account")';
Session.Abandon();
} else {
x = "Cancel";
}
}
I want to prevent is that , after logging out , then I click the back navigation button , I don't want to go back to the previous page.
Browsers can cache content locally. So no matter what you are doing on your server, after logging out, if the user clicks on the Back button, the browser can decide to get the last page from the local cache and display it.
In order to prevent this behavior you could serve all controller actions that require authentication with cache disabled. This can be achieved by decorating them with a custom [NoCache] filter. This filter will ensure that the proper response headers are set when serving actions that require authentication to prevent the browser from caching them.
This being said, please note that the Session.Abandon(); call should be done on your server - inside your Logout controller action that is supposed to clear the authentication cookies and session state.
Session.Clear and Session.RemoveAll are identical; the latter just calls the former. They immediately remove all items stored in the session, but the session itself survives. Session_OnEnd does not fire.
Session.Abandon doesn't actually clear the values immediately, it just marks the session to be abandoned at the end of the current request. You can continue to read the values for the rest of the request. If you write to the session later in the request, the new value will be quietly discarded at the end of the request with no warning. Session_OnEnd fires at the end of the request, not when Abandon is called.
I am having a hard time deciding on an appropriate way to Perform some server side functionality and then redirecting to the same View in my ASP.Net MVC project.
I am trying to call an Action after the selected index changed client side event of my combobox.
One way I can think of is to change the window.location to the url of my Action and pass the data i need via the query string like this
function SelectedIndexChanged(s,e)
{
window.location.href = "/MyController/MyAction?" + s.GetValue();
}
I also see lots of people saying you should use jquery ajax for this
function SelectedIndexChanged(s,e)
{
$.ajax({
url: 'MyController/MyAction',
data: { value: s.GetValue() },
success: function(){
alert('Added');
}
});
}
My Action looks something like this where i set some cookie values using the value and Set View bags values depending on the selected index.
public ActionResult SelectedIndexChanged(string value)
{
//Do some processing
//Set cookie values
SetViewBags(value);
return Redirect(Request.UrlReferrer.ToString());
}
Is there a better approach to accomplish my task, I am leaning more towards changing the location.href as it is simpler, but i'm not sure if this is good practice?
EDIT
To Clarify this Combobox is a Devexpress MVC extension so I will have to handle the "SelectedIndexChanged" client side event.
This Combobox is also on my layout page so it appears on every view in my project. So when it is changed i will need to to call the same Action no matter what page it is on
As you've indicated that your form is in your layout (not a view), I recommend you look at using a view partial. Fortunately, MVC has already provided an example with their view partial (can't remember the name) that has the login and logout buttons. If a user clicks logout, some javascript is fired and the form is submitted. This will redirect the user; however, you could also send the original address (referrer) as a parameter to your server method and then redirect to that page afterward.
You could always use an Html.Action
function SelectedIndexChanged(s,e)
{
#Html.Action("ActionName", "ControllerName", {optional route values})
}
I want to set session variable using javascript/jquery in my apsx page.
Afterwards,I want to use that session variable in other page using jquery.
Can anyone help me for this?
Thanks,
Priya
You cannot set directly with javascript you need server side code for it. you can make an ajax call and pass parameter and set session there.
You can set the session variable value in hidden field when page is initially loaded like this:
<asp:HiddenField ID="HDSessionValue" runat="server" Value'<%#Session["CustomerID"]'/>
Now you can easily get the value from jquery or javascript like this:
$(document).ready(function(){
var SessionValue=$('#HDSessionValue').val();
alert(SessionValue);
});
You have two cases here ,
1) If you want to set the value of Session in client side on the page load it self you can use the hidden field to pass on the client side .
2) If you want to set the value on the client side without going to back to post back , you can opt for the AJAX method
you can assign the value of session variable to JS variable but to assign a value to session variable you need something like ajax working on server side
My project is composed by 2 html pages:
index.html, which contains the login and the registration form.
user_logged.html, which contains all the features of a logged-in user.
Now, what I want to do is a control if the user is really logged in, to avoid the case where a user paste a url in the browser and can see the pages of another user.
hours as now, if a user paste this url in the browser:
www.user_loggato.html?user=x#profile
is as if logged in as user x and this is not nice.
My html pages both use js files that contains scripts.
I decided to create a global variable called logged inizialized to false and change the variable to true when the login is succesful.
The problem is that the variable, remains false.
here is the code:
var logged=false; (write in the file a.js)
while in the file b.js I have:
function login() {
//if succesfull
logged=true;
window.location.href = "user_loggato.html?user="+ JSON.parse(str).username + #profilo";
Now with some alerts I found that my variable logged is always false. Why?
Javascript is not the way to go, as it runs on the client side. Even if there would be a way to share javascript variables between different requests, the user could manipulate them.
You have to take a server side technique for this (maybe PHP with sessions).
JS variables will reset on every submit/refresh. You could use sessionStorage or cookies for this purpose. For example:
Put this in your login form:
function login() {
window.sessionStorage[logged] = true;
window.location.href = "user_loggato.html?user="+ JSON.parse(str).username + #profilo";
}
And in your user_loggato.html, you can retrive it like:
function getLoginStatus() {
return window.sessionStorage['logged'];
}
Hope this helps.
I need to enable a script which is present in a .net master page, in only selected html pages that use this master page. can this be achieved by declaring a variable in javascript of html pages where I need this script and set the variable to some value, so that I can enable the scripts in master page only when variable is NotNullorEmpty? Does some one know if this works. If so how to get javascript variable in html, in to .net master page ?
There are 2 ways I can think of.
The first if to assign the variable to a hidden input field. Which can be accessed in the Request.Form.
html
<input type="hidden" value="your value" name="Hidden1" id="Hidden1"/>
javascript
document.getElementById('Hidden1').value = "an other value";
C#
var myValue = Request.Form["Hidden1"];
The second is saving the variable into a cookie which can be accessed in Request.Cookies.
var myValue = Response.Cookies["Cookie1"].Value;
The most flexible form of this that I have seen is to render a JSON object directly to the page as script (adding any other script you might need also), then making the javascript code fill in a hidden field with JSON data on form submit for the server to parse.
Here are the basic steps:
Create an empty hidden field for the server to read when the client submits, but send it to the client empty.
Create a string which is the script and JSON data you need to send to the client. (Use the JavaScriptSerializer .NET class.)
Fill a LiteralControl with the script tag and its contents. (This works well in the OnPreRender step, but you can do it elsewhere.)
Include JSON2.js (it's all over the web - get it from a trusted source)
Write javascript code to fill the hidden field on submit, using JSON2.stringify() to push any javascript object into that field.
On the server, you can again use JavaScriptSerializer to read the values from the submitted object.
What you are basically wanting to do is test for javascript.
There are a few ways to do this, but I would use both a server-side and client-side cookie.
In your global.asax's onbeginrequest, test for a server-side cookie of "js-test-s"
Cookie Exists, check for "js-test-c"
"js-test-c" Cookie Exists, JS enabled
"js-test-c" No Cookie, JS disabled
Cookie doesn't exist...
Set the "js-test-s" cookie
output a simple html document...
[html]
[head]
[meta refresh tag set to 1 second /]
[script to set "js-test-c" cookie, then force refresh /]
[/head]
[body][/body]
[html]
Browser will refresh the request with one or both cookies set.
WARNING: You may want to store the original request details, and redirect to another location in case cookies are disabled.
I might be not understanding the question correctly but as far as I can tell the easiest way to do this is by creating a property on the master page and then setting it on all pages that need to execute the script:
In Master page
public bool EnableScript
{
set
{
if (value == true)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "startup", "alert('test');", true);
}
}
}
In all pages that need to run javascript that use the current master page:
protected void Page_Load(object sender, EventArgs e)
{
this.Master.EnableScript = true;
}
If you have to output your JavaScript on every page, even on the once that don't execute it (why?) then just add it as a function and then inside your property add a code to call that function, and set your property to true on all pages that require JavaScript to execute.