ASP.NET MVC2 - Detect javascript, store result in session variable
I want to render specific HTML in a partial view based on whether javascript is enabled or not. My idea was to some how detect whether javascript was enabled and store it in a session variable which I can then test for in my view e.g.
<div class="product">
<%
// if Javascript is enabled, load the images asynchrously, otherwise load them directly.
string imgHtml = "<img id=\"myImage\" src=\"{0}\" alt=\"MyImage\" />";
if ((bool)Session["jsEnabled"])
imgHtml = String.Format(imgHtml, Url.Content("~/Content/images/ajax-loader.gif") + "\" onload=\"loadImageAsync(this, '" + Url.Content开发者_如何学Python("~/Content/images/" + Model.thumbnail) + "')");
else
imgHtml = String.Format(imgHtml, Url.Content("~/Content/images/image.jpg"));
%>
<div><%= imgHtml %></div>
</div>
From what I have read most seem to suggest using a hidden field and setting it's value in javascript, however, I don't quite understand how I can get this to work in MVC unless I post the data somewhere (this particular view isn't within a form).
Correct me if I'm wrong, but it looks like you are trying to use progressive enhancement. If that is the case, then the proper thing is to have the page render the most basic version (the .gif), and then attempt to have the more advanced technology (javascript) itself supersede/overwrite it with the more advanced (javascript) version.
You could use JavaScript to make an AJAX call to a method that sets the session variable. If JS isn't enabled then no call is made and no variable is set.
I would also pull all that code out into a helper method that just takes the src of the image as it'll make your views a lot cleaner.
精彩评论