如何在jquery方法中获取asp.net会话值?

Rav*_*avi 12 c# asp.net asp.net-mvc jquery

我想在ASP.NET MVC视图页面中的jquery方法中访问Session值.见下面的代码,

$('input[type=text],select,input[type=checkbox],input[type=radio]').attr('disabled', '<%= Session["CoBrowse"].ToString() %>');
Run Code Online (Sandbox Code Playgroud)

如何在jquery中获取Session值.

小智 18

$('input,select').attr('disabled','<%=Session["CoBrowse"].ToString() %>');
Run Code Online (Sandbox Code Playgroud)


Fer*_*min 8

不确定这是否是最佳路由,但在您的aspx页面中,您可以创建一个返回会话变量值的方法,例如

服务器端:

using System.Web.Services;
 [WebMethod(EnableSession = true)]
public static string GetSession()
{
   return Session["CoBrowse"].ToString();
}
Run Code Online (Sandbox Code Playgroud)

然后使用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);
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 你能从静态方法中访问Session吗?我认为你不能. (3认同)

Kob*_*obi 8

很多评论:

  1. 你不能"从jQuery访问会话".您使用MVC和asp.net来创建HTML页面(使用JavaScript).Session是服务器端对象,JavaScript在客户端运行.
  2. 看看jQuery的选择器.它们有像有用的选择:checkbox,:text等等.
  3. 你的代码产生的JavaScript你期望:它编译,运行,并产生JavaScript和truefalse在正确的地方.
  4. 这不是禁用元素的方法.如果元素具有"禁用"属性,则无论该值如何,它都将被禁用.<input type="checkbox" disabled="false" />也是一个禁用的复选框,因此您的控件始终处于禁用状态.
  5. 如果这是您选择的方式,请考虑:

    var isCoBrowse = <%= Session["Name"].ToString().ToLower() %>;
    if(!isCoBrowse) //disable controls
      $(":text,:checkbox,:radio").attr("disabled","disabled"); //standard.
    
    Run Code Online (Sandbox Code Playgroud)

    这将生成客户端JavaScript代码:

    var isCoBrowse = true;
    
    Run Code Online (Sandbox Code Playgroud)

    并且,要启用元素:

    $("input").removeAttr("disabled");
    
    Run Code Online (Sandbox Code Playgroud)

此外,有更好的方法来实现这一目标.您是否考虑过禁用服务器端的控件?


fya*_*vuz 6

<input id="sessionInput" type="hidden" value='<%= Session["name"] %>' />

var getSessionValue = $('#sessionInput').val();
Run Code Online (Sandbox Code Playgroud)