Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
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.
Posted

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. Add using statement for System.Web.Services namespace in code behind :
using System.Web.Services;

3. Add WebMethod to code behind to get system datetime :
C#
[WebMethod]
public static string GetSystemDateTime()
{
    return DateTime.Now.ToString();
    //OR return HttpContext.Current.Session["SessionName"].ToString();
}

4. Now call WebMethod from javascript function and bind return value to the textbox :
XML
<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.
 
Share this answer
 
Comments
VC.J 9-Oct-14 6:57am    
yes this is another way and it is better than I have suggested below as you can get the Updated session value.
You can store the DateTime in a session like
C#
Session["DateTimeDemo"] = DateTime.Now;


Then use this to a viewmodel which is used for the viewpage.
C#
 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.
C#
<input type="text" id="datetime" data-val="@Model.DateTimeDemo"> </input>


and then in your script you add:
C#
var datetimeForDemo = $("#datetime").attr('data-val');


I guess you get some help from this
Thanks
:)
 
Share this answer
 
v2
Try this
C#
protected void Page_Load(object sender, EventArgs e)
        {
            Session["sample"] = DateTime.Now; 
        }


in aspx

XML
<script type="text/javascript">
var sessionValue= '<%= Session["sample"]%>';
                   alert(sessionValue);
</script>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900