MVC 5 c# hide url parameter - c#

$.ajax({
type: "POST",
url: "#Url.Action("SignInUp")",
data: JSON.stringify({ email_add: email_add ,}),
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response.result == 'SignUp') {
alert("Opp`s its look like you dont have an access for this website");
window.location = response.Urls;
}
else
{
alert("Success fully login");
window.location = response.Url;
}
}
});
hi guys I`m new in mvc5 c# and i in counter this problem i want to hide my url parameter. any can help me thank you for advance
this is my code:
public ActionResult SingInUp(string email_add)
{
bool obj = db.tblUsers.Any(x => x.email_add.Equals(email_add));
if (obj)
{
tblUser user = db.tblUsers.Single(x => x.email_add == email_add);
Session["email_add"] = user.email_add;
Session["fname"] = user.fname;
Session["lname"] = user.lname;
return Json(new { result = "Redirect", Url = Url.Action("Check", "ProjectV3") });
}
else
{
return Json(new { result = "SingUp", Urls = Url.Action("SignUp", "ProjectV3", new { email_add = email_add}) });
}
}
This is i want to hide

If you want to effectively hide something from the client Url you will need to find a way to either mask it, or store it somewhere on the server that can be captured on the next request.
There are many places you can store this data on your server but really the obvious ones are.
Cookies
TempData
Now TempData may seem like the obvious choice as it persists across requests and is cleared from the TempData when accessed. Which is also its downfall, lets say you set the TempData in your SingUpIn method, then return the JsonResul which I am assuming is then used via JavaScript for a redirect. Then you redirect to this page and then pull the value of the TempData dictionary it is subsequently removed. So if the person ends up on the SingUp page and for some reasons decides to refresh the page the value in the TempData wont be found again.
Now this can be handled by resetting the TempData property on each read. So basically you read the TempData item then you reassign the TempData entry.
Here is some very basic code that [basically] works and doesnt show the email in the url.
public ActionResult SignUpIn(string email_acct)
{
//pretend i tested for a real user
TempData["email_acct"] = email_acct;
var r = new { result = "SingUp", Urls = Url.Action("SingUp") };
return Json(r);
}
public ActionResult SingUp()
{
if (!TempData.ContainsKey("email_acct"))
{
//no temp data email.. maybe redirect.. who knows!!
return RedirectToAction("Index");
}
//read the temp data entry..
string emailAcct = TempData["email_acct"].ToString();
//reset the temp data entry
TempData["email_acct"] = emailAcct;
return View(new SingUpModel { EmailAccount = emailAcct });
}

Unless you want to go to POST rather than URL parameters you are stuck. If you just want to hide some of the implementation details you could encode the parameter to obfuscate its meaning.
return Json(new { result = "SingUp", Urls = Url.Action("SignUp", "ProjectV3", new { email_add = Base64Encode(email_add)}) })
...
public static string Base64Encode(string plainText) {
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
You would end up with a URL like: http://localhost:1126/ProjectV3/SignUp?email_add=cGtleWJpcmQ5NUBnbWFpbC5jb20=. You could obviously change the name of the parameter to hide its intent.

Related

Pass a variable from a view to a controller action method and then to another method in the same ASP.NET MVC controller

One of my views get a token from an API when customer places an order. I would like to pass that token variable to an action method in a controller. Once it gets to that action method I need to pass it to another method inside the same controller. How do I accomplish that?
This is what I have so far - this is the view:
<script type="text/javascript">
document.addEventListener('jrig.begin', function () {
jrig.events.on('bag.confirmed', (bagConfirmResponse) => {
console.log('This is the token number: ' + bagConfirmResponse.token);
//Go to the thank you page
var url = '/purchase/thank-you/order/' + bagConfirmResponse.token;
var bagConfirmResponsetoken = bagConfirmResponse.token;
//Testing passing the token variable to the PurchaseController.cs
$.ajax({
type: "POST",
url: "/Purchase/GetTokenFromView",
data: '{Token: ' + JSON.stringify(bagConfirmResponsetoken) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
});
window.location.href = url;
});
});
</script>
Then once the token variable makes it to the PurchaseController it gets passed to this JsonResult below:
public JsonResult GetTokenFromView(string Token)
{
ViewBag.PassedToken = Token;
return Json(Token);
// I have tried redirectToAction as well but the value becomes null.
}
I want to be able to create a view bag there so that I can pass that value for the token to the ActionResult that comes after the GetTokenFromView JSON result which is the ActionResult "Thank you".
public ActionResult Thankyou(string slug, string Token, string email)
{
slug = "thank-you";
Console.Write(Token);
//Token = ViewBag.PassedToken;
var savedToken = Token;
Console.Write(savedToken);
var url = "https://application.ecomapi.com/api/purchases/" + savedToken;
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
return View();
}
The view bag that I created to pass the token, no longer has a value once we enter the "Thankyou" action result. So there is no way for me to reference it anymore.
Is there a way I can maybe pass that piece of data a better way. Perhaps even pass it from view to the controller without having to use ajax ?
I have tried to pass it directly from the view to the thankyou method but when I do that it nulls out the value once the program gets to where it needs to call that token. During debugging it jumps back and forth from JsonResult GetTokenFromView to ActionResult Thankyou eventually making the value null again when I need it, so I figured I don't pass it directly from view to thankyou, but pass it to another method first instead.
Thanks.
You can use ViewData or TempData to persist your variables from one Controller action to another:
public JsonResult GetTokenFromView(string Token)
{
ViewData["PassedToken"] = Token;
return Json(Token);
// I have tried redirectToAction as well but the value becomes null.
}
And access it in your Thankyou method like this:
public ActionResult Thankyou(string slug, string Token, string email)
{
slug = "thank-you";
Console.Write(Token);
//Token = ViewBag.PassedToken;
//Get your ViewData variables here
if (ViewData["PassedToken"] != null)
{
Token=ViewData["PassedToken"];
}
var savedToken = Token;
Console.Write(savedToken);
var url = "https://application.ecomapi.com/api/purchases/" + savedToken;
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
return View();
}

Cant do redirect (ASP.NET MVC)

I need to do redirect to controller
Here is my controller
[HttpPost]
public ActionResult Index(string question1, string question2, string question3, string question4, string question5, string question6, string question7, string question8, string question9, string question10, Int32 id)
{
QuestionBlock question = new QuestionBlock
{
Question1 = question1,
Question2 = question2,
Question3 = question3,
Question4 = question4,
Question5 = question5,
Question6 = question6,
Question7 = question7,
Question8 = question8,
Question9 = question9,
Question10 = question10,
Interview_Id = id,
};
//TempData["id"] = id;
db.QuestionBlocks.Add(question);
db.SaveChanges();
return Json(new { Result = "Success", Message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
I try to do it like this
return RedirectToAction("Index", "Questions", new { id = id });
I have this AJAX call in my View. Maybe trouble in it?
<script>
$('.click').on('click', function () {
$('.content').toggle();
});
var counter = 0;
$(document).ready(function () {
$('#save').click(function () {
save();
});
});
function save()
{
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
question1: $('#Question1').val(),
question2: $('#Question2').val(),
question3: $('#Question3').val(),
question4: $('#Question4').val(),
question5: $('#Question5').val(),
question6: $('#Question6').val(),
question7: $('#Question7').val(),
question8: $('#Question8').val(),
question9: $('#Question9').val(),
question10: $('#Question10').val(),
},
url: '#Url.Action("Index", "Questions")',
success: function (da) {
if (da.Result === "Success") {
alert('Вопросы сохранены');
} else {
alert( 'Error'+ da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
</script>
But redirection not works. Where is my trouble?
Maybe I need to do it not in controller?
Thank's for help
Your current code is returning a JSON response with 2 properties and your main view code is making an ajax call to this action method. So the JSON response returned from the action method will be handled in the success handler of your ajax call. It will not do a redirect unless you explicitly do so.
Even if you replace the return Json with return RedirectToAction, It does not makes sense to use it with the Ajax call. The whole idea of ajaxifying the page is to avoid the traditional page submit - reload experience and replace it with partial page upload behavior (better user experience)
If you absolutely want to redirect to another page, you can do that in the success event handler. But like i mentioned earlier, it does not makes sense to do an ajax post then. Do a normal form post!
if (da.Result === "Success") {
window.location.href="Give the new Url you want to navigate to here";
}
You can use the UrlHelper class to generate the correct url to the other action method and send that as part of your JSON response.
var urlBuilder = new UrlHelper(Request.RequestContext);
var url = urlBuilder.Action("Index", "Questions",new { id= id});
return Json(new { Result = "Success", Message = "Saved Successfully",RedirectUrl=url });
Now in your ajax call , read the RedirectUrl property
if (da.Result === "Success") {
window.location.href=da.RedirectUrl;
}
Have you tried just like this without writing Questions.:
return RedirectToAction("Index", new { id = yourvalue });
EDIT:
Otherwise you can try this:
return RedirectToAction( "Index", new RouteValueDictionary(
new { controller = controllerName, action = "Index", id = id } ) );

Ajax post JSON data to MVC getting error Unexpected token P

This has been driving me nuts. I have a page where I need to make a JSON post to a controller, it will process it and return an excel file for download. So far it appears to be running correctly, but when it returns to the ajax call, I get an parsererror and the message "Unexpected token P." I have tried so many different configurations and call methods (standard MVC ActionRequest to WebApi post) and none of them change. Here is the code I'm running.
JavaScript:
var treatmentplan = {"PlanRecordStatusId":"1","PlanRecordDateBegin":"","PlanRecordDateEnd":"","ClientClaimNumber":"","PatientNumber":0,"requestAction":3};
$.ajax({
//global: true,
//url: '/home/ExcelRpt',
url: '/api/TreatmentPlanExcel',
type: 'POST',
dataType: 'json',
data: treatmentplan,
//contentType: 'application/json; charset=utf-8',
success: function (data) {
//var msg = data.Message;
//$('#results').html(msg);
$("#tmpFrame").attr('src', 'URL-TO-EXCEL-FILE');
}
, error: function (jqXHR, exception, error) {
if (jqXHR.status === 0) {
alert('Not connect.n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.n' + jqXHR.responseText);
}
$('#log').html(error.message);
}
});
Here is the C# code (both WebApi and MVC controller version), I am not going to include my ToExcel extension, I know this part works it's just a matter of getting it to download when it's returned. It is reaching this code, generates data and returning. I just need to see what the heck is going on. If there is a prefered way of making the call, let me know as well (WebApi or MVC)
C#
Web Api version
public HttpResponseMessage Post(TreatmentPlanRequest tpRequest) {
tpRequest.Verify();
List<TreatmentPlan> tpl = DataAccess.GetReportDap(tpRequest).ToList();
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var package = tpl.ToExcel("TreatmentReport");
var fileStream = new MemoryStream();
package.SaveAs(fileStream);
fileStream.Position = 0;
result.Content = new StreamContent(fileStream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
Here is the MVC controller version
[HttpPost]
public ActionResult ExcelRpt(TreatmentPlanRequest tpRequest) {
tpRequest.Verify();
List<TreatmentPlan> tpl = DataAccess.GetReportDap(tpRequest).ToList();
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var package = tpl.ToExcel("TreatmentReport");
var fileStream = new MemoryStream();
package.SaveAs(fileStream);
fileStream.Position = 0;
var fsr = new FileStreamResult(fileStream, contentType);
fsr.FileDownloadName = "TreatmentReport";
return fsr;
}
From here, I have no clue as to why this isn't working. I have searched high and low on Google on how to do this in MVC (I use to do this with web forms and never had an issue). I am guessing my issue is on the return or
Change your Success method to open a new window with the URL instead of setting a frame in the current window.
So this:
$("#tmpFrame").attr('src', 'URL-TO-EXCEL-FILE');
becomes:
window.open('URL-TO-EXCEL-FILE');
In the vast majority of cases, this should do exactly what you're looking for. Occasionally, depending on specific browser settings, users may get a "Popup Blocked" message, but that rarely happens in this scenario in the apps that I've worked with.
EDIT:
After additional clarification, there is a second issue. Data returned from the server must be in the same format as the .ajax() method is expecting it, in this case 'JSON'. Instead of returning a FileStreamResult from your Action, try returning a JSON object which has the URL you'll need to call to generate the Excel file.
return Json(new { URL = 'URL-TO-EXCEL-FILE' });
Then, follow the suggestion in my original response.
I would like to thank Kris Hatcher for the solution on this. He suggested making two ActionResults. One that builds a query string from the parameters of the initial request. It returns a full URL with the parameters. It then does a Window.Open() using the returned url.
With all the examples I found, this was the only one that worked for me. Here's how the code works.
JavaScript:
function TestWebApiReport() {
var reportData = GetReport();
$.ajax({
url: '/home/ExcelResults'
, data: reportData
, type: 'POST'
, dataType: 'json'
, success: function (data) {
window.open(data.URL);
}, error: function (jqXHR, exception, error) {
alert("GRRRRRR!!!")
}
});
}
It creates the JSON data, then posts it to a JsonResult. Here's the controller code.
C#
[HttpPost]
public JsonResult ExcelResults(ReportRequest tpRequest) {
StringBuilder sb = new StringBuilder();
bool firstIn = true;
sb.AppendFormat("{0}/Home/ExcelRpt", Request.Url.Scheme + "://" + Request.Url.Authority);
foreach (var prop in tpRequest.GetType().GetProperties()) {
if (prop.GetValue(tpRequest, null) != null) {
if (firstIn) {
sb.AppendFormat("?");
firstIn = false;
} else {
sb.AppendFormat("&");
}
sb.AppendFormat("{0}={1}", prop.Name, prop.GetValue(tpRequest, null));
}
}
return Json(new { URL = sb.ToString() });
}
You go back to the JavaScript, you'll see the return data uses the URL to do a Window.Open(). Then the excel file is created. Here's the last call (ActionResult).
[HttpGet]
public ActionResult ExcelRpt(ReportRequest tpRequest) {
if (tpRequest.requestAction != RequestAction.Report) {
throw new Exception("Did not use action request type of 'Report'.");
}
tpRequest.requestAction = RequestAction.Report;
List<Report> tpl = DataAccess.GetReportDap(tpRequest).ToList();
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var package = tpl.ToExcel("Report");
var fileStream = new MemoryStream();
package.SaveAs(fileStream);
fileStream.Position = 0;
var fsr = new FileStreamResult(fileStream, contentType);
fsr.FileDownloadName = "TreatmentReport.xlsx";
return fsr;
}
ReportRequest is a class I have and ToExcel(), I extended the List item. Now this works pretty well.

MVC Jquery POST data, redirect to url from ActionResult

I am currently working with mvc. I have a page with more than one button on, which does complicate things a little. However the button I am using calls a jquery function to post data to the controller. This works as expected and data reaches the action and the action does everything expected except redirect.
The function posts data to the controller, or allows the controller to see the values and build up a url to then redirect to. However the redirect doesnt work, and the function calls a success function as expected. If I put the data return into an alert the code for the page is returned in the alert window not the url.
Here is the code:
<input type="submit" value="Assign" name="Assign" onclick="doRedirect()" />
function doRedirect() {
var action = '#Url.Action("Redirect")';
//alert(action);
var opt = {
type: "POST",
data: {
Team: $('#Team option:selected').val()
},
url: action,
success: RedirectSuccess
};
jQuery.ajax(opt);
}
function RedirectSuccess(data) {
if (data != undefined) {
data;
}
}
public ActionResult Redirect(string Team)
{
var hostName = "http://localhost/test/testpage.aspx?";
var team = "&Team=" + Team;
var filterUrl = Team;
return Redirect(filterUrl);**//this doesnt work**
}
Instead of sending back a redirect result from the action, try sending back the URL you want to redirect to. On the client side, you read the response of the request, and do the redirect by setting window.location.href to the URL you get back from the server.
In your action, you could return the URL as JSON for instance:
return Json(new { url: filterUrl });
And in your success callback, you do this to redirect:
if (data !== undefined && data.url !== undefined) {
window.location.href = data.url;
}
This is what I did instead.
public string Redirect(string Team)
{
var hostName = "http://localhost/test/testpage.aspx?";
var team = "&Team=" + Team;
var filterUrl = hostname + Team;
return filterUrl;
}
function RedirectSuccess(data) {
if (data != undefined) {
window.location = data;
}
}
and on my search success

How do I force session timeout or a logout of a user when the app auto saves in an asp.net mvc 2 application?

I've seen this question asked a few ways and the solutions are generally for other languages and don't apply to ASP.NET MVC 2.
I am using Jquery & Jquery forms to auto-save user data at a set interval. I still want the application to be able to time out, but the auto-saves via jquery forms keep refreshing the server.
My initial idea to fix this was pretty simple. I've already got an ActionFilter I use to see if the session expires. Well, the session won't ever expire; however, I just keep track of how many auto saves occurr based on a value in session and when it reaches a limit (specified in the web.config), it does a:
filterContext.Result = new RedirectResult("~/Account.aspx/LogOn");
Well, this doesn't work because the auto save is doing an ajaxFormSubmit to call the action in the first place. I've tried changing the action to redirect to the login page, but the same thing happens....it just doesn't do a redirect. The only thing the action can return is a Json result. In my latest version (code below) I'm setting the json return value to false and calling a redirectToLogin() function to send the page over to the login page. It doesn't work and i'm not sure why.
Any thoughts on this would be most helpful.
Excerpt of code that sets up the interval for autosaving on the view (placed just before the form is closed):
<%
double sessionTimeoutInMinutes = double.Parse(ConfigurationManager.AppSettings["SESSION_TIMEOUT_IN_MINUTES"].ToString());
double maxContiguousAutoSaves = double.Parse(ConfigurationManager.AppSettings["MAX_CONTIGUOUS_AUTO_SAVES"].ToString());
double autoSaveInterval = (sessionTimeoutInMinutes / maxContiguousAutoSaves) * 60 * 1000;
%>
<%= Html.Hidden("autoSaveInterval", autoSaveInterval) %>
<script type="text/javascript">
$(document).ready(function() {
var autoSaveFrequency = $('[id=autoSaveInterval]').val();
//alert(' Auto Save Interval in miliseconds: ' + autoSaveFrequency);
setInterval(
"initAutoSave('AutoSaveGoals', 'message')"
, autoSaveFrequency);
});
</script>
"AutoSaveGoals" goals is the name of one of my actions. It handles the post, updates certain items in session, and calls the repository.update. It is defined below:
[HttpPost]
public ActionResult AutoSaveGoals(Data data)
{
Data sessdata = Data();
sessdata.MpaGoals = data.Goals;
sessdata.MpaStatus = data.MpaStatus;
sessdata.StartPeriodDate = data.StartPeriodDate;
sessdata.EndPeriodDate = data.EndPeriodDate;
sessdata.AssociatePassword = data.AssociatePassword;
try
{
_repository.update(sessdata);
}
catch (Exception e)
{
LogUtil.Write("AutoSaveGoals", "Auto Save Goals Failed");
LogUtil.WriteException(e);
}
if (!autoLogOffUser(RouteData.GetRequiredString("action")))
return Json(new { success = true });
else
return Json(new { success = false });
}
The initAutoSave function is javascript that uses Jquery & Jquery Forms plugin. Here it is:
function initAutoSave(targetUrl, messageDivId) {
var options = {
url: targetUrl,
type: 'POST',
beforeSubmit: showRequest,
success: function(data, textStatus) {
//alert('Returned from save! data: ' + data);
if (data.success) {
var currDateAndTime = " Page last saved on: " + getCurrentDateAndTime();
$('[id=' + messageDivId + ']').text(currDateAndTime).show('normal', function() { })
}
else {
alert('redirecting to login page');
redirectToLogin();
//$('[id=' + messageDivId + ']').text(' An error occurred while attempting to auto save this page.').show('normal', function() { })
//alert('ERROR: Page was not auto-saved properly!!!!');
}
}
};
$('form').ajaxSubmit(options);
}
I try doing a javascript redirect in redirectToLogin() but it doesn't seem to get the url or something behind the scenes is blowing up. Here is how it's defined:
function redirectToLogin() {
window.location = "Account.aspx/LogOn";
}
best way to solve this is to have your code always return an Json result, i use a model called StandardAjaxResponse that has an ID, a Message and an answer answer is always false unless my code completes in the correct way and sets this to true. Any errors from try / catch are placed into the message field, so if !data.Answer and the Message is equal to not loggged in the you can then location.href to the login page, without getting the login page as your ajax response.
for example:
public class AjaxGenericResponse{
public bool Answer {get;set; }
public int Id {ge; set; } // this is for cases when i want an ID result
public string Mesage {get;set;} // this is so i can show errors from ajax
}
the controller / action
public JsonResult DoAutoSave(Data data){
var JsonResults = new AjaxGenericResponse{Answer=false};
// do code here to save etc
// no matter what always return a result, even if code is broken
return Json(model);
}
your Javascript:
$.ajax({
url:"",
dataTYpe: 'json',
success:function(data){
if(data.Answer) {
// all is good
} else {
if(data.Message === "logout') { href.location=('login'); } else { alert(data.Message); }
}
}
});
thats one solution anyway!
Stupid me. Thanks for your response minus, but I think our solutions coincided for the answer. My issue was I didn't have the right url to redirect to in the redirectToLogin method. I've made minor tweaks, and presto, its redirecting.
Javascript changes:
function redirectToLogin(url) {
window.location = url;
}
function initAutoSave(targetUrl, messageDivId) {
var options = {
url: targetUrl,
type: 'POST',
beforeSubmit: showRequest,
success: function(data, textStatus) {
//alert('Returned from save! data: ' + data);
if (data.success) {
var currDateAndTime = " Page last saved on: " + getCurrentDateAndTime();
$('[id=' + messageDivId + ']').text(currDateAndTime).show('normal', function() { })
}
else {
alert('redirecting to login page');
redirectToLogin(data.url);
//$('[id=' + messageDivId + ']').text(' An error occurred while attempting to auto save this page.').show('normal', function() { })
//alert('ERROR: Page was not auto-saved properly!!!!');
}
}
};
$('form').ajaxSubmit(options);
}
Action changes
if (!shouldAutoLogOffUser(RouteData.GetRequiredString("action")))
return Json(new { success = true, url = "" });
else
return Json(new { success = false , url = Url.Action("LogOff","Account").ToString() });
The shouldAutoLogOffUser checks a session variable that was updated by an action filter to track the # of contiguous auto saves and handles the logic to see if that value has exceeded the max # of contiguous autosaves allowed. The action filter checked the actionname for 'AutoSave' and if it found it, the counter was incremented. Otherwise the counter was reset to 0 (a non autosave post occurred).
One more random question. If this application were loaded in an IFrame and the window.location call is made, would the IFrame content be changed or the entire page (the container in essence) be changed? Our company is looking to run some of our asp.net mvc 2 apps in IFrame's via websphere portal (yeah, I know....it's not my choice).
Now this is just absurd...So, I was looking over my applications (I've got several going to QA soon) and noted that I've already solved this very question with a much better solution - it was ALL handled in an ActionFilter. I wanted this from the getgo when I asked this question, but to have already implemented it, forgot about that, AND ask again on Stack Overflow...well, I hope my memory issues helps somebody with this. Below is the full action filter code. As always, I'm open to criticism so mock it, revise it, copy it, etc, etc.
public class UserStillActiveAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
int sessionTimeoutInMinutes = int.Parse(ConfigurationManager.AppSettings["SESSION_TIMEOUT"].ToString());
int maxContiguousAutoSaves = int.Parse(ConfigurationManager.AppSettings["MAX_CONSEC_SAVES"].ToString());
int autoSaveIntervalInMinutes = int.Parse(ConfigurationManager.AppSettings["AUTO_SAVE_INTERVAL"].ToString());
string actionName = filterContext.ActionDescriptor.ActionName;
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
HttpContext currentSession = HttpContext.Current;
LogAssociateGoalsSessionStatus(filterContext.HttpContext, actionName);
if (actionName.ToLower().Contains("autosave"))
{
int autoSaveCount = GetContigousAutoSaves(filterContext.HttpContext);
if (autoSaveCount == maxContiguousAutoSaves)
{
var result = new RedirectResult("~/Account.aspx/LogOff");
if (result != null && filterContext.HttpContext.Request.IsAjaxRequest())
{
//Value checked on Logon.aspx page and message displayed if not null
filterContext.Controller.TempData.Add(PersistenceKeys.SessionTimeOutMessage,
StaticData.MessageSessionExpiredWorkStillSaved);
string destinationUrl = UrlHelper.GenerateContentUrl(
result.Url,
filterContext.HttpContext);
filterContext.Result = new JavaScriptResult()
{
Script = "window.location='" + destinationUrl + "';"
};
}
}
else
{
RefreshContiguousAutoSaves(filterContext.HttpContext, autoSaveCount + 1);
}
}
else
{
RefreshContiguousAutoSaves(filterContext.HttpContext, 1);
}
}
private int GetContigousAutoSaves(HttpContextBase context)
{
Object o = context.Session[PersistenceKeys.ContiguousAutoUpdateCount];
int contiguousAutoSaves = 1;
if (o != null && int.TryParse(o.ToString(), out contiguousAutoSaves))
{
return contiguousAutoSaves;
}
else
{
return 1;
}
}
private void RefreshContiguousAutoSaves(HttpContextBase context,
int autoSavecount)
{
context.Session.Remove(PersistenceKeys.ContiguousAutoUpdateCount);
context.Session.Add(PersistenceKeys.ContiguousAutoUpdateCount,
autoSavecount);
}
private void LogAssociateGoalsSessionStatus(HttpContextBase filterContext, string actionName)
{
AssociateGoals ag = (AssociateGoals)filterContext.Session[(PersistenceKeys.SelectedAssociateGoals)];
bool assocGoalsIsNull = false;
bool assocGoalsInformationIsNull = false;
if (ag == null)
{
assocGoalsIsNull = true;
assocGoalsInformationIsNull = true;
}
else if (ag != null && ag.AssociateInformation == null)
assocGoalsInformationIsNull = true;
}
}
always use double quote in java script and jquery to avoid browser specific issues
like
dataTYpe: 'json' must be as "dataTYpe:"json"

Categories