javascript popup blocker and ajax callback - C# MVC app - c#

There are 2 requirements in a secure website in which a form is being posted to an url:
The form will be posted to a new window if authentication ticket is still valid, otherwise the same window will redirect user to the login page.
Posting the form to new window will not invoke popup blocker.
I have gone as far as writing an ajax action to get correct answer on whether auth is still valid or not. But I'm unable to get the redirect code to come outside the script execution context and thus avoid popup blocker. Please help!
JavaScript:
$('#someSystem').click(function () {
//deferred promise?
auth().done(function (result) {
//need to move below code outside this callback without side effects
if (result == 'true') {
var form = $('#ssoForm');
form.submit();
}
else {
window.location.href = "/account/login";
}
});
return false;
});
function auth() {
return $.ajax({ url: '/account/isauthenticated', method: "POST" });
}
HTML for already authenticated user
<form action="/sso/somesystem" id="ssoForm" method="post" target="_blank">
...
<div id="someSystem">Continue</div>
</form>

I don't believe you will be able to do anything short of adjusting the pop-up block to avoid it. If the js could do that it would almost completely defeat the purpose of the blocker. Also you should think about the security of doing your redirect in js because the code is in user space. The user could cancel the redirect from their browser.
Instead why not do the check on the server and use
RedirectToAction()

After reading several jQuery posts and even signalR, this codeproject.com article was the most helpful for my case. It seems there is a simpler way to handle this. Developer does not know whether the authentication is valid or not at a given time, but definitely knows after how long it will expire. This knowledge can be hard coded in a JavaScript and an alert can be sent to the user preemptively (setTimeout), instead of waiting for them to click and then try to figure out. This approach will not let me disturb the popup blocker.

Related

Prevent resending form without page.redirect

maybe some of you know the problem, that a form gets resubmitted if pressing refreshing the browser by pressing F5.
I am looking for a way to prevent this, and all I have found is the solution to do a redirect on the same page after submit
Response.Redirect(Request.RawUrl);
This DOES work, but my problem is, that I need to inject javascript into a placeholder after postback, and so this information is lost because of the Redirect.
PlaceHolder p1 = this.NamingContainer.Parent.FindControl("phPostScript") as PlaceHolder;
GenerateJsTag(script,p1);
Response.Redirect(Request.RawUrl);
Is there a way I can prevent a resubmit without Redirect?
Thanks
Is there a way I can prevent a resubmit without Redirect?
Even if there is , you should stick to that approach which is redirect after submit.
Regarding JS after post back , I believe that you want to see those JS output even after refresh after redirect.
What you can do is to redirect to Request.RawUrl+"#someValue" and then in the pageLoad (not within IsPostBack) you can inject again those scripts , knowing that you already showed that to the user via that hashkey ( could be cookie also , or query string , doesn't really matter) - or to show a message like ("Message was already accepted"...) or something like that.
Try adding following JavaScript code to your aspx page.
Also, you should not be trying to disable F5 since there are many users out there who may need to use F5 during browsing with your website.
//bind keydown event to method that disables F5
$(document).on("keydown", PreventRefresh);
function PreventRefresh(e) {
var code = e.which || e.keyCode;
if (code === 116) {
e.preventDefault();
}
}

Clear POST data after submission so user can't click Back in browser

My form when redirected to the thank you page after completion seems to retain all the data in the values field so if the user clicks back everything is there meaning they can just resubmit it and its super annoying.
if (emailSent) {
Response.BufferOutput = true;
Response.Redirect("MYDOMAIN/redirect.aspx");
};
Above is where I redirect after the form has been submitted. For my code to pull the data I am using:
Request.Form[randomFormField]
When I redirect and then click back everything is there.
$(".submitBut").click(function() {
$(this).closest('form').find("input[type=text], textarea").val("");
window.location.href('MYREDIRECTDMAIN/redirect.aspx');
});
Above is another one of my attempts
I have tried a variety of different things and nothing seems to work. I need an ASP.NET solution or C# or JQuery.
Javascript on page load: clear all form fields
Uhm....
$(document).ready(function() {
$(':input').val('');
});
References:
Input
Clearing

MVC 4 with jQuery Mobile page seems to be caching and controller method not being called

EDIT
Figured it out.. $.ajaxSetup({ cache: false }); wasn't working because i had data-ajax set to turned off on the form and therefore i wasn't able to set no cache ajax on it.. just for completeness if anybody knows how to get this done WHILE dada-ajax is set to false then please post so here
Something else that I just tried and it worked was to simply add data-ajax="false" to any link that you want a page refresh on. Meaning that if I have data-ajax="false" on a link it will always refresh the page before showing it!
For example the link I had a problem with was
Add a new weekly update
and the problem was that for some reason that page was caching and always showing the cached page.. So one of the easy fixes was to add data-ajax="false" to it and that forced a reload of the page everytime
Add a new weekly update
````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````
Question:
I have a options menu which brings up a form which also has a cancel and submit button.
Once the form is submitted there is certain validation that runs and if something is missing it returns to the form with some validation text.
Now if I click the cancel button at anytime i should be brought back to the options menu and if I click on the same button that brings up the form i should see a brand new clean form and this works fine if I do it before the validation.
The problem is that if I submit a non valid form which returns with the error validation messages and THEN press cancel it seems that the page becomes cached or something similar because from that point on anytime I click on the form options menu button the same form shows up each with the validation errors and data. I put a break point in the method that returns the form View() and they are never hit so for some reason it skips the entire method which creates a new form and somehow just shows the old page.
The cancel button is the following
Cancel
Does anybody know what is happening? is it being cached somehow when it returns to the same page with the validation errors??
** EDIT **
I Tried adding [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] in front of the controller by to no avail..
I also now added
$.ajaxSetup({ cache: false });
to the top of my $(document).ready(function () but that also does not seem to be doing anything, do I just put it there or do I have to call it somehow?
I checked System.Web.HttpContext.Current.Cache and the page doesn't show up there.
Have you tried setting the output cache options on the controller action like
[OutputCache(Duration=600,VaryByParam="id")]
You might also want to try making sure jquery is not caching the request as well. You can globally turn off jquery ajax caching using the information here: How to set cache: false in jQuery.get call
You can try using $.mobile.changePage() to transition to the page, it allows you to set some options, one of which is reloadPage.
reloadPage (boolean, default: false) Forces a reload of a page, even if it is already in the DOM of the page container. Used only when
the 'to' argument of changePage() is a URL.
Source: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
You could work this into your link with something like:
<script>
function changeMyPage(url) {
$.mobile.changePage(url, { reloadPage : true });
}
</script>
Cancel
jquery Mobile pulls multiple pseudo-pages into the DOM at one time and normally deletes (.removes()) a pseudo-page after you've navigated away from it. It however sounds like that's not happening so you may need to use my above code (or something similar) to force a refresh of the page.
You need to clear your ModelState before hand.
This should work:
if (ModelState.IsValid)
{
//saving
if (result > 0)
{
**ModelState.Clear();**
return View(new CategoryViewModel());
}
}
How to Clear model after submit the data in database in MVC3

How to "PRE-PROCESS" ajax call before showing the mvc view?

I'm not so expert with ajax, so I find it hard to look for the better answer. I've tried creating separate ".js" file that contains the call for rest service (for validation of user session), but it doesn't work.
My goal is to validate user session before loading my views (in MVC). The only way to use the logic of validating the given session with the database is to call a rest service via url using ajax.
This code works well (inside Home View):
<script type="text/javascript">
$(function () {
$.get('#Url.Action("GetSession", "Auth")', function (getdata) {
if (getdata.UserID && getdata.SessionID && getdata.SourceIP) {
$.post('http://website.com/Rest/Authenticate/ValidateUserSession', JSON.stringify(getdata), function (response) {
if (response == false) { window.location.replace('#Url.Action("SignUp", "Auth")'); }
});
} else {
window.location.replace('#Url.Action("SignUp", "Auth")');
}
});
});
</script>
<h2>
Home</h2>
#*The content here should not appear, unless session is validated.*#
The only problem is that, the process of validation takes 3 to 5 seconds, so the user sees the Home page before the ajax call returns the result whether the validation was successful or not. If validation/response returns false it will redirect to sigup page.
I don't know what is the best practice with this process. For now I jsut don't want the Home view show to the user unless session is validated. Hope I'd explain it well. Please suggest if you have the better idea.
Additional info:
If possible, I like doing this:
<script type="text/javascript">
if(!validated()){
window.location.replace('#Url.Action("SignUp", "Auth")');
}
</script>
<h2>
Home</h2>
#*The content here should not appear, unless session is validated.*#
Why can't you consume the rest service at server side ? Technically there should be no reason for not being able to do that. Here's a tutorial discussing exactly that : http://codebetter.com/johnvpetersen/2012/03/22/accessing-a-asp-net-webapi-rest-service-from-asp-net-mvc/
That should take care of everything. If for some reason that's not possible for you, then you can do the following,
Make your home page a partial view.
Instead of loading home page, load an empty page with processing icon (or whatever message you want to show.)
Talk to the REST service and if got the reply then load Home page's partial view using JQuery else load sign up partial view.
Here's an article discussing how to load MVC partial views using JQuery: http://www.codeproject.com/Articles/34221/JQuery-Partial-Views-in-ASP-NET-MVC

Calling FormsAuthentication.SignOut() method using jquery

I am using Asp.Net/C# in my project.I am using Forms Authentication.Currently I call FormsAuthentication.SignOut() on click of Asp.Net button.It works well , but my requirement is that I need to log out a user from horizontal menu option
Logout
That would be Html menu , so how do I call FormsAuthentication.SignOut() method when a user clicks Logout from the menu bar.Is there any solution possible or any other technique.
Any suggestions are welcome.
Thanks
FormsAuthentication.SignOut() is a server side code and you cannot directly invoke it from client side (i.e. browser) - instead, you need to create a URI that will do the same for you.
For example, you can have AJAX service that will call above code or simply speaking, you can have logout.aspx page that will call FormsAuthentication.SignOut() in say page_load. Such a URI can be invoked from jquery to get you what you want.
In your case, you should simply have a link to logout aspx page in your logout menu (or in menu click, write document.location = "/logout.aspx" which essentially means navigating to log-out page).
here you go:
$('#logout').click(function () {
$.ajax({
url: '/logout',
success: function () {
document.location = '/logged_out';
}, error: function () {
alert('Logout failed');
}
});
return false;
});

Categories