views:

637

answers:

4

Hi,

I have an asp.net application with an aspx page. In page_Load event of the aspx page,m handling some code which is based on the hidden variable value from the javascript(assigning result of javascript to hidden variable). I am calling the javscript in page_load of child page and in the immediate statement, m making use of the hidden variable value for processing.When I access hidden variable value, m getting default value only.

Please suggest me any of handling the scenario.( i need to execute the javascript and get the result into hidden variable; both in page_load event only)

Hidden Variable declaration:

<asp:HiddenField runat='server' ID='hdnDate' Value='0' />

javscript:
function getCDate()
{
    var nowDate    = new Date();  
    var curr_month = nowDate.getUTCMonth();
    curr_month ++;
    var dt = curr_month + "/" + nowDate.getUTCDate() + "/" +nowDate.getFullYear()+ " " + nowDate.getUTCHours()+":" +nowDate.getUTCMinutes()+":" +nowDate.getUTCSeconds();
    document.getElementById("ctl00_ContentPlaceHolder1_hdnDate").value = dt;          
    return true;
}

code behind file:
protected void Page_Load(object sender, EventArgs e)
    {
             Page.ClientScript.RegisterStartupScript
                (this.GetType(), "alert", "getCDate();", true);
             DateTime dt=Convert.ToDateTime(hdnDate.Value);
            dt.AddDays(10);    //getting error here because dt contains01/01/0001       
        }

Thanks Rupa

A: 

You cannot call javascript in Page_Load. It is client side thing so should come from browser only. You can check if page is postback using IsPostBack property of Page object like this:

if(IsPostBack)
{
   //this is coming from browser so you javascript  might have been
   //called and proper value set in hidden field.
}
TheVillageIdiot
A: 

Javascript is run on the client side, so can't run in the Page_Load event on the Server.

From the looks of your code, I'm pretty sure you don't need javascript, you can just put the value into a SessionVariable as:

Session.Add("DateRendered", DateTime.Now.AddDays(10).ToString("MM/dd/YYYY"));

And then retrieve it later. ASP.net takes care of storing it in the Request/Response.

Mark Kadlec
A: 

This is sample comment by wewaerdfsadf

Benarji
A: 

RegisterStartupScript will register your block of script for the next page load. if you just want some value to be transferred to .cs page write a static method on the .cs and call it from javascript using PageMethods.MethodName();

Vinay Pandey