Setting a ASP.NET Session in jquery.click() - c#

When a user select a tab on my site, I would like to store which tab they are on so that I can send them back there after the page refreshes. I have this at the moment (excuse the bad coding atm, I am testing the concept):
$("#index_0_li").click(function() {
<%= Session["SelectedIndex"] = "0" %>
});
$("#index_1_li").click(function() {
<%= Session["SelectedIndex"] = "1" %>
});
var index = <%= Session["SelectedIndex"] %>;
The problem is, because <%= %> doesn't wait for the on click, the index is always being set to 1.
Does anyone have any ideas on how I can achieve what I am trying to do?
Thanks.

Just use client-side session - aka "cookies".
Set the cookie on the click event, then when you submit the page (or "post back"), this cookie will be sent with the HTTP request, allowing you to read it via Request.Cookies.

As El Ronnoco said, if you want the selected tab in the ASP.NET Session, then you need to send it back to the server. You could do this with an AJAX call, or you could include it with another post you do in your application.
However, if you simply want to maintain the selected tab for the client, you can do as RPM1984 suggested and store it in a cookie (or other local storage if HTML5 is allowed) and select that the tab last recorded in cookie/local storage upon loading the page. The following is off the top of my head so might have syntax errors (I'd need to see your tab and other markup to do a working solution):
$("#index_0_li").click(function() {
localStorage.setItem('SelectedTab', '#index_0_li');
});
$("#index_1_li").click(function() {
localStorage.setItem('SelectedTab', '#index_1_li');
});
$(document).ready(function() {
var index = localStorage.getItem('SelectedTab');
if (index !== null) {
$(index).click();
}
});

The click function is client side javascript.
You cannot set a serverside variable on the client.
You should set the selectedindex serverside, for example using a jquery post.

Related

Block page from being viewed if not from redirect in ASP.NET/C#

I have created a page that loads a page based on an ID you pass from a previous page. However, I don't want someone to be able to just enter the .aspx page manually into the address bar. I only want the user to be able to view this page if they clicked the button that got them there. I have heard of Document.Referrer, but I am not using any Javascript in my pages and this does not provide enough security. Are there any built-in functions or tricks to achieve this?
Thanks in advance!
I would look at the cross page post:
http://msdn.microsoft.com/en-us/library/ms178139(v=vs.90).aspx
Specifically you can check for it: (FROM MSDN):
if(PreviousPage != null)
{
if(PreviousPage.IsCrossPagePostBack == true)
{
Label1.Text = "Cross-page post.";
}
}
else
{
Label1.Text = "Not a cross-page post.";
}
You could try checking HttpContext.Request.UrlReferrer (Request.UrlReferrer on MVC). If they enter the URL directly it will be null. If they are sent from another page it will have the referrer URL.

jquery tab asp.net staying on tab after postback 0x800a01b6

Hello i need to stay on a jquery tab after asp.net postback, but nothing what i found here or somewhere else in the web works for me.
I tried:
Staying on current jQuery tab across post back?
and
Jquery postback, maintain same tab after postback
but also some other sources.
Everytime when im changing
$("#tabs").tabs();
to something like:
$(function () {
$("#tabs").tabs({
show: function() {
var selectedTab = $('#tabs').tabs('option', 'selected');
$("#<%= hdnSelectedTab.ClientID %>").val(selectedTab);
},
selected: <%= hdnSelectedTab.Value %>
});
});
With hiddenfield etc. i get this error 0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'tabs'.
When im Using the jquery.cookie.js file with this code:
$("#tabs").tabs({ cookie: { expires: 1 } });
i dont get an error but i dont stay on the tab after postback.
You can give your input button a css class.
#inputField {
display:none !important;
}
Save this as yourCssClass.css
document.getElementById("inputField ").className += "yourCssClass";
Add this to your JavaScript
I found out what the Problem was, I inserted jquery on the end of my master page because of that somehow it overwrote the jqueryui file in that specific aspx file. After i added the jqueryui.js file after the jquery.js everything worked fine.

Invalid ViewState when using jQuery tabs

I have a fairly simple page with a set of jQuery tabs, the content of some is called via ajax. I also have a search box in the masterpage in my header.
When I open the tabbed page the search box works fine. However once I have clicked on one of the ajax tabs the search box fails to work with an "Invalid Viewstate" yellow screen of death.
I believe this is because the ajax page is replacing the __VIEWSTATE hidden input with its own.
How can I stop this behaviour?
UPDATE: I have noticed that the YSOD only appears in IE and Chrome, Firefox doesn't seem to have the same issue. Although how the browser influences the ViewState, I'm not sure.
UPDATE: I've put a cut down version of the site that shows the issue here: http://dropbox.com/s/7wqgjqqdorgp958/stackoverflow.zip
The reason of such behavior is that you getting content of the ajaxTab.aspx page asynchronously and paste it into another aspx page. So you getting two instances of hidden fields with __VIEWSTATE name and when page posted back to server theirs values are mixing (might depends on how browser process multiple controls with same name on submit). To resolve this you can put second tab's content into a frame:
<div id="tabs">
<ul>
<li>Default Tab</li>
<li>ajax Content</li>
</ul>
<div id="tabs-1">
<p>
To replicate the error:
<ul>
<li>First use the search box top right to search to prove that code is ok</li>
<li>Then click the second ajax tab, and search again.</li>
<li>N.B. Chrome / IE give a state error, Firefox does not</li>
</ul>
</p>
</div>
<iframe id="tabs-2" src="ajaxTab.aspx" style="width:100%;" ></iframe>
</div>
Also, I'm not sure but this seems like error in the Web_UserControls_search control. In my opinion, NavBarSearchItemNoSearchItem_OnClick method must be refactored as below:
protected void NavBarSearchItemNoSearchItem_OnClick(object sender, EventArgs e)
{
var searchFieldTbx = NavBarSearchItemNo;
var navBarSearchCatHiddenField = NavBarSearchCatHiddenField;
var term = searchFieldTbx != null ? searchFieldTbx.Text : "";
if (term.Length > 0) //There is actually something in the input box we can work with
{
//Response.Redirect(Url.GetUrl("SearchResults", term));
Response.Redirect(ResolveClientUrl("~/Web/SearchResults.aspx?term=" + term + "&cat=" + navBarSearchCatHiddenField.Value));
}
}
Draw attention that we resolving client url when redirecting to search results page and instead of navBarSearchCatHiddenField use navBarSearchCatHiddenField.Value as cat parameter.
I guess that you use AJAX to fill the content of the tab. So in this case, content of your tab will be replaced by the new one from ajax and certainly _VIEWSTATE will be replaced. At server, do you use data from ViewState? In the "static tabs", you should prevent them auto reload by using cache:true
Your issue is that with your ajax call you bring in a complete ASPX page. Including the Form tag and its Viewstate. If you remove the Form tag from ajaxTab.aspx you will see everything works fine. asp.net does not know how to handle two Form tags in one page. Same goes for hidden Viewstate fields. You cannot bring in a full aspx page via ajax. Just bring in the content Div you want to display and you`ll be good to go.

How to stop browser back button showing a page I have left

I am using MVC2 and VS2010.
We have created a web application but want to stop any browser re-visiting pages after the page has been left.
We want to do this so that someone who is using a public computer who then leaves can feel safe. We dont want the scenario that a following user can just use the back button to view the first uses pages.
I have tried [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
This seems to work fine and I get a Web Page Expired. But if I press the browser back button again, the page will be displayed.
I have quite a similar situation myself in wanting to prevent a browser back situation and have researched a few different solutions. The first and worst being a Java script function which takes the user back to the page they were on if they click the back button in the browser. It hides the problem rather than solving it but thought id mention it. The code as follows:
<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>
This works for Firefox, Chrome and IE ok. You can just put this in your master page.
Many people will tell you this is not the way to do things however as it intrudes on the well known browser behaviour etc etc
So my second suggestion is something I have seen here:
Disable browser cache for entire ASP.NET website
Which will not cache anything which is more inline with what you are wanting I think.
Another idea would be to pass a page or session token around and on actions check the token - if its invalid reroute to an error page. That would at least prevent a new user doing anything with the previous page.
Id be interested to know how you solved this, if you have solved it.

How do I set a value to the Session in asp.net on an onClick event of a normal htmlElement?

I need to make a Function that receives a Session Key and a Session Value and call this function on a normal HTML onClick event. When this function is called the Session variable is assigned the Key I sent with the Value I sent. So far I have this:
<script runat="server" type="text/C#">
protected void setSessionValue(string key, string value)
{
Session[key] = value;
}
</script>
But when I try to call if like so:
onclick="setSessionValue('itemID','3345');"
Its not working and giving me an error. Any help? I'm using c# and asp.net but I can't use code behind and need to work everything off the page.
You cannot set anything to the session from the client because session in stored on the server.
You are trying to invoke a server method from a client side javascript. You can either do as what Oded suggested or, you can use the ASP.NET Ajax to achieve the same.
The below link would be a good starting point on how to do this using ASP.NET Ajax.
ASP.NET Ajax Exposing Webservices to Ajax
Update 1:
Another useful link
You are trying to call the server side (C#, VB.NET) code from the client side (Javascript).
This is not possible.
You can change your HTML control to be server side, by adding the runat="server" attribute on it - you will also need to change the type to one that is recognized serverside, namely <asp:HtmlLink />.
Try using
OnServerClick="setSessionValue('itemID','3345');"
instead of
onclick="setSessionValue('itemID','3345');"
Ok I managed to find a solution on my own thanks to all of your submissions, listen to this. I added a javascript function as follows:
function setSessionValue(key, value) {
$.post('setSession.aspx?key=' + key + '&value=' + value);
}
and added an aspx file with the following code within it:
<%# Page Language="C#" %>
<%
Session[Request["key"]] = Request["value"];
%>
Basically this worked just fine, all I needed was a little jQuery. Thanks to all for your suggestions.

Categories

Resources