Reputation: 1313
I want to access a Session value in jquery method in the ASP.NET MVC view page. See the below code,
$('input[type=text],select,input[type=checkbox],input[type=radio]').attr('disabled', '<%= Session["CoBrowse"].ToString() %>');
How can I get the Session value in jquery.
Upvotes: 13
Views: 105177
Reputation: 9
Easy! when you know how:
@Html.Encode(Session("classificationTitle"))...and in the .js file:
var classificationTitle = document.getElementById('classificationTitle').innerHTML;
sorry - I can't post the full html as this site strips out angle brackets :(
Upvotes: -1
Reputation: 129
<input id="sessionInput" type="hidden" value='<%= Session["name"] %>' />
var getSessionValue = $('#sessionInput').val();
Upvotes: 6
Reputation: 36071
Not sure if this is the best route but within your aspx page you could create a method that returns the value of your session variable, e.g.
Server side:
using System.Web.Services;
[WebMethod(EnableSession = true)]
public static string GetSession()
{
return Session["CoBrowse"].ToString();
}
then call this method client side using jQuery:
$.ajax({
type: "POST",
url: "./Default.aspx/GetSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result){
('input[type=text],select,input[type=checkbox],input[type=radio]').attr('disabled', result.d);
}
});
Upvotes: 8
Reputation: 4797
If that Session variable is sensitive data (which in this case it probably isn't), I would not use this solution as it would show the Session data when you looked at the javascript source. If it is sensitive session data, accessing it via a web method (see above answer) is probably best.
Upvotes: 1
Reputation: 137997
Many comments:
:checkbox
, :text
, etc.true
or false
on the right place.<input type="checkbox" disabled="false" />
is also a disabled check box, so your controls are always disabled.If that is the way you choose anyway, consider:
var isCoBrowse = <%= Session["Name"].ToString().ToLower() %>;
if(!isCoBrowse) //disable controls
$(":text,:checkbox,:radio").attr("disabled","disabled"); //standard.
This will produce the client-side JavaScript code:
var isCoBrowse = true;
And, to enable an element:
$("input").removeAttr("disabled");
Also, there are much better ways to accomplish this. Have you considered disabling the controls on server side, if possible?
Upvotes: 8
Reputation:
$('input,select').attr('disabled','<%=Session["CoBrowse"].ToString() %>');
Upvotes: 18