Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable to external JS file in asp.net?

I want to use variable of default.aspx.cs in default.aspx file in the script and i successfully it like

public partial class default: System.Web.UI.Page
{
    public string _file = string.Empty;
    public string _img = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        _file = "~/videos/myVideo.mp4";
        _img = "~/images/myImg.png";
    }
} 

and in my default.aspx file

<html>
  <body>
    <div id="dv_video"></div>
  </body>
</html>

<!-- jw Script -->
<script src="../jwplayer/jwplayer.js"></script>
<script type="text/javascript">
    jwplayer("dv_video").setup({
        file: '<%= _file %>',
        image: '<%= _img %>',
        height: 500,
        width: 850
    });
    </script>
<!-- jw Script -->

this code is working fine, I want to shift this script code to external javascript file extras.js how can i access _file, _img variable on that javascipt file thats looks like

jwplayer("dv_video").setup({
    file: '<%= _file %>',
    image: '<%= _img %>',
    height: 500,
    width: 850
});

Edited

I have use this code to pass parameter to the js file extras.js

<script type="text/javascript" src="<%= Page.ResolveClientUrl("~/jwplayer/extras.js") %>">
    _image: '<%= _img %>';
    _file320: '<%= _file320 %>';
    _file480: '<%= _file480 %>';
</script>

and this code to use parameter on js file

jwplayer("dv_video").setup({
    image: window._image,
    sources: [{
        file: window._file480,
        label: "480p HD",
        "default": "false"
    },
    {
        file: window._file320,
        label: "360p SD",
        "default": "true"
    }],
    height: 500,
    width: 850
});
like image 282
Usf Noor Avatar asked Oct 23 '25 00:10

Usf Noor


1 Answers

There's several ways to do that. You can either define a global JS variable like this:

<script type="text/javascript">
_file = '<% _file %>';
_image = '<% _image %>';
</script>

Then you can use those variables in your external JavaScript file like this:

var file = window._file;
var image = window._image;

Another solution is to add those variables into your HTML as data values. Like the following:

<html>
  <body>
    <div id="dv_video" data-file="<% _file %>" data-image="<% _image %>"></div>
  </body>
</html>

Then you can get those data-values in your JS like this:

var image = $('#dv_video').data('image');
var file = $('#dv_video').data('file');
like image 152
Mikkel Avatar answered Oct 24 '25 13:10

Mikkel