Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top