Using WebGrid with sortable columns, the call to the controller bypasses the Session - session

In ASP.NET MVC 4, I have a multipage app that does some security checking on the first page, stores the results in a Session variable, then uses OnActionExecuting on every Controller to test the Session variable as I move from page to page. One of the views uses a WebGrid with sortable columns. When I click on the column header to engage the sort, I get a call to the view's default Action, but, in OnActionExecuting, the Session variable is not there. It appears to have created a new session. My logic then treats it as a security failure.
I have not yet found where this click (to sort) is being handled, so that's my first issue - perhaps I could influence what is being passed in. Alternatively, (and ideally), there is a setting in WebGrid that I have missed that would maintain the current Session. I am away from the code at the moment, but those are the things I haven't found yet.
What I am looking for is a way to preserve the Session while using the WebGrid sortable column feature.
Additional Information: In the view, the WebGrid's <th> elements are all anchors, like <a href="/MyController?sort=MyColumnName?sortdir=ASC">

(I could use a better answer, but this worked for me)
Since the value in the heading is actually an anchor, I was able to discover that the QUERY_STRING always contains "sort=". Thus, I could at least check for this and restore the missing security variable to the Session, based on the assumption that, if I am getting this query string, the user has passed the security test before.
(filterContext.RequestContext.HttpContext.Request.Params["QUERY_STRING"].Contains("sort="))
I'm still thinking that WebGrid should not be starting a new session for me, but at least this workaround will get me going.
NOTE FOR FUTURE REFERENCE: We were using the <system.web> setting <sessionState cookieless="true">. Apparently, when WebGrid sets up its links for sorting, it does not detect that setting, thus it does not include the session id in the URL. This is why WebGrid was starting a new session for us.

Related

Using laravels {{old}} on dynamically created inputs

I have a form which allows a user to create an unlimited number of fields. If this forms fails validation I want the user to return to this page with the form populated with their previous input values - i.e. I want these fields to persist.
With a normal form I could do this with {{ old 'title' }}, however, these additional fields are being generated through JavaScript and so I cannot add this PHP snippet. What is the best way for me to retrieve these previous input values?
3 ways to do this, cache, sessions and cookies.
cache and sessions are server side which is much better for security, however it will take extra time and effort for setting up, but if the data is not sensible and can be passed within cookies, better to the cookies.
The best thing about cookies for your current situation is: you can set it up directly from your front end JS code.

Link change SESSION var

I have a listing page for an e-commerce website with various items (item_list.php). This page is generated with a PHP loop and displays each item inside a <li> element. Every item is a link to the same page, called item_details.php .
When clicking on the link i want to run a script that changes a SESSION var to a certain $id (which will be excracted from the <li> itself with .innerHTML function) and then allowing the browser to move into the next page (item_details).
This is needed so i can display the proper information about each item.
I think this is possible with Ajax but I would prefer a solution that uses JS and PHP only.
(P.S.This is for a University project and im still a PHP newbie, i tried searching for an answer for a good while but couldn't find a solution)
No JS or other client-side code can set session values, so you need either an ajax call to php, or some workaround. This is not a complete answer, but something to get you thinking and hopefully going on the project again.
The obvious answer is just include it in the link and then get it in PHP from the $_GET -array, and filter it properly.
item title
If, however, there is some reason this is not a question with an obvious answer:
1.) Closest what you're after can be achieved with a callback and an ajax call. The idea is to have the actual link with a click function, returning false so the link doesn't fire at once, which also calls an ajax post request which finally will use document.location to redirect your browser.
I strongly advice against this, as this will prevent ctrl-clicks causing a flawed user experience.
Check out some code an examples here, which you could modify. You will also need an ajax.php file which will actually set the session value. https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#product-click
2.) Now, a perhaps slightly better approach, if you truly need to do this client-side could be to use an click handler which instead of performing an ajax call or setting session directly, would be to use jQuery to set a cookie and then access this data on the item_list.php -page.
See more information and instructions here: https://www.electrictoolbox.com/jquery-cookies/
<script>
$('product_li a).click(function(){
$.cookie("li_click_data", $(this).parent().innerhtml());
return true;
});
</script>
......
<li class="product_li">your product title</li>
And in your target php file you check for the cookie. Remember, that this cookie can be set to anything, so never ever trust user data. Test and filter it in order to make sure your code is not compromised. I don't know what you want to do with this data.
$_COOKIE['li_click_data'];
3.) Finally, as the best approach, you should look at your current code, and see if there is something you can re-engineer. Here's a quick example.
You could do the following in php to save an array of the values in the session on each page load, and then get that value provided you have some kind of id or other usable identifier for your items:
// for list_items.php
foreach($item as $i) {
// Do what you normally do, but also set an array in the session.
// Presuming you have an id or some other means (here as item_id), to identify
// an item, then you can also access this array on the item_details -page.
$_SESSION['mystic_item_data_array'][$i['item_id]] = $i['thedata'];
}
// For item_details.php
$item_id = // whatever means you use to identify items, get that id.
$data_you_need = $_SESSION['mystic_item_data_array'][$item_id];
Finally.
All above ways are usable for small data like previous page, filters, keys and similar.
Basically, 1 and 2 (client-side) should only be used, if the data is actually generated client-side. If you have it in PHP already, then process it in php as well.
If your intention is to store actual html, then just regenerate that again on the other page and use one of the above ways to store the small data in case you need that.
I hope this gets you going and at least thinking of how to solve your project. Good luck!

How to save property after tombstoning?

I have some property OwnerId that has each page in my application. I need these property to create HttpWebRequest and get some data. But when the application deactivated and activated again the page as deleted and created again, so these property is 0. I can't save these property in PhoneApplicationPage.State , because these property is different for different pages, so when I go twice back I can get error. I think to take it property after application activated from NavigationService.BackStack pages.But I'm not sure it is right. How can I do it ?
Aram .. thanks for explaining the question better.
Now, while your application is in the foreground, how are you managing all these different OwnerIDs? A collection? I am guessing you don't have multiple instances of the same page; but rather pass query parameters along to indicate which OwnerID/UserID should be used to display appropriate user info. You could put the whole collection in State dictionaries with a key & hydrate/dehydrate during the application lifecycle. Makes sense?
Thanks!
I'm not 100% clear on whether you need a setting for each page or just a single setting for the app. In either case your best option (IMO) is IsolatedStorageSettings (http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings(v=vs.95).aspx)
If you just need a single setting then there's no problem but if you need one for each page you will need to do something ugly like using the page name as the key.

CakePHP session data cleared on paginator sort

My session data is being saved in my form as expected.
However, when I run a sort on any column of my results, my form session values are cleared.
I am calling in my search form through en element as it's used on specific locations of the site.
Does anyone know why pagination is clearing out my session? Is this standard Cake?
The paginator sort elements are simply a link generated by the paginator and won't consider any of your form data. The first thing you need to make sure that you're doing is tell the paginator to include any URL paramters for the current page in the url it generates. Put this anywhere in the view before you call any of the $paginator functions.
$paginator->options(array('url' => $this->passedArgs));
Secondly, make sure that your search parameters are being included in the URL. It sounds like they probably aren't. I just answered another question on the best practices of search result URLs here: CakePHP Search Results Best Practices
I solved this:
CakePHP session ID path or other method to share the results of a url - recommendations welcome

where should I save a complex MVC application UI state?

I've been having a look at several MVC frameworks (like rails, merb, cakephp, codeignitier, and similars...)
All the samples I've seen are basically plain and simple CRUD pages, carrying all the infr needed in the querystring and the posted field values.
I've got a couple of apps made with some sort of framework built with classic asp.
This framework handles some CRUD stuff a little more complex than the examples I found.
Something like master-detail, filtering by example, paging, sorting and similars.
I have a controller class that it's just a finite state machine, that goes thru diferent states (like new, browse, filter, show, etc.), then performs the appropiate action depending on the event raised and finally retrieves the neede info to the calling page.
To achieve this I have several hidden inputs to keep the state of the web page (like current id, filter criterias, order criterias, previous state, previous event, well, you get the idea)
What do you think would be the finnest approach to achieve this kind of funcionality?
hidden inputs built in the view and used from the controller??? (I guess that would be the equivalent of what I'm doing right now in classi asp)
--
(added in response to tvanfosson)
basically, my question refers to the third category, the context-dependent setting (in respect to the other two categories I agree with you) the info I was storing in hidden fields to store them on the querystring, I guess that when you click on the "next page" you include everything you need to save in the querystring, right? so that piece of query string gets appended in each and every link that performns some kind of action...
I'm not sure, what are the advantages and disadvantages of using the querystring instead of hidden inputs???
I use different strategies depending on the character of the actual data. Things that are preferences, like default page size, I keep in a Preferences object (table) that is associated with the current logged in user and retrieve from there when needed.
Persistent settings associated with the current logon, like filter settings for a page, are stored in the user's session. Generally these are things that if a user sets them in the current session they should remain sticky. I think filter settings and visibility are like this. If I filter a list, navigate away from it to drill down into a particular item, then come back to the list, I want my filter settings to be reapplied -- so I make it part of the session.
Context-dependent settings -- like the current sort column or page number, are controlled using query parameters. Paging and sort controls (links) are built with the appropriate query parameters to "do the right thing" when clicked and pass any necessary query parameters to maintain or update the current context of the control. Using the query parameters allows you to use an HTTP GET, which is bookmarkable, rather than a POST. Using hidden form parameters makes it much harder for the user to save or enter a URL that takes them directly where they want to go. This is probably more useful for sorting than it is for paging, but the principle applies equally.

Resources