如何在c#后面的代码中从java脚本获取会话值 [英] How to get the session value from java script in code behind c#

查看:57
本文介绍了如何在c#后面的代码中从java脚本获取会话值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在尝试从java脚本中的会话中获取值(系统日期时间)并绑定到文本框,如所需的日期时间。









先谢谢。

Hi,

I am trying get the value (system date time) from session in java script and bind to text box like date time required.




Thanks in Advance.

推荐答案

要获取系统日期时间,您可以从javascript调用PageMethod。



按照以下步骤操作:

1.添加脚本管理器到.aspx并将EnablePageMethods设置为true:

To get system datetime you can call PageMethod from javascript.

Follow the steps :
1. Add script manager to .aspx and set EnablePageMethods to true:
<asp:ScriptManager runat="server" EnablePageMethods="true">



2.在代码后面添加System.Web.Services命名空间的using语句:


2. Add using statement for System.Web.Services namespace in code behind :

using System.Web.Services;



3.将WebMethod添加到代码后面以获取系统日期时间:


3. Add WebMethod to code behind to get system datetime :

[WebMethod]
public static string GetSystemDateTime()
{
    return DateTime.Now.ToString();
    //OR return HttpContext.Current.Session["SessionName"].ToString();
}



4.现在从javascript函数调用WebMethod并将返回值绑定到文本框:


4. Now call WebMethod from javascript function and bind return value to the textbox :

<script type="text/javascript">
        function ShowDate() {
            PageMethods.GetSystemDateTime(function (result) {
                document.getElementById("TextBoxID").value = result;
            });
        }
    </script>



如果有帮助,请不要忘记将其标记为答案。


Please don't forget to mark as answer if it helps you.


您可以存储会话中的DateTime如

You can store the DateTime in a session like
Session["DateTimeDemo"] = DateTime.Now;





然后将其用于用于视图的viewmodel。



Then use this to a viewmodel which is used for the viewpage.

 var viewModel = new DemoModel{
 DateTimeDemo = Convert.ToDateTime(Session["LoggedInTime"]);
//Any other values ...if any..
 }
return View(viewModel);



您可以将其存储为隐藏字段。


And you can store that as a hidden field.

<input type="text" id="datetime" data-val="@Model.DateTimeDemo"> </input>





然后在你的脚本中添加:



and then in your script you add:

var datetimeForDemo =


#datetime)。attr(' data-val');
("#datetime").attr('data-val');





我猜你从这里得到一些帮助

谢谢

:)



I guess you get some help from this
Thanks
:)


这篇关于如何在c#后面的代码中从java脚本获取会话值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆