0

I'm trying to use the following syntax to pass a variable from my ascx.cs file to my javascript :

in the ascx.cs :

protected string DateFinMax = WebConfigurationManager.AppSettings["DateFinMax"].ToString();

in the javascript :

$(function () {
    $(".datepickerValidTo").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy',
        minDate : 0,
        maxDate: <%= DateFinMax %>,
        showOn: 'both',
        buttonImage: '../css/smoothness/images/calendar.gif',
        buttonImageOnly: false
    }, $.datepicker.regional['fr']);
});

The value of the variable in the code behind is good however I can't seem to pass it to my js file. I've tried to put simple and double quote aswell but nothing worked. The js file is called as follow at the end of my ascx file :

<script src ="js/datepicker.js"></script>

Any help would be appreciated. Thanks

1 Answer 1

3

The technique you are using is only for passing variables from code behind to the corresponding aspx markup. It is not possible to render something from code behind in the linked javascript file. However what you can do is create a variable on the page, and use it in the js file.

On the page, say on Page_Load, do something like this:

string script = string.Format("var DateFinMax = {0};", this.DateFinMax);
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "initDateFinMax", script, True);

And in the script file simply use it, since this is just another javascript variable:

minDate : 0,
maxDate: DateFinMax,
showOn: 'both',

As long as your script is added on the bottom of the page, variable should be visible.

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect thanks, I misunderstood the example and thought I could pass it to my js files. Would you recommand using this or storing the value in an HiddenField and access it with getElementById in the javascript ?
@WizLiz, using HiddenField for this looks a bit hacky. Hidden fields in their essence are for sending info to server, not receiving from it. Registering variable is a cleaner way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.