Using server side method in an external JavaScript file
In a c# aspx proj开发者_JAVA百科ect. I can reach a static method on client side with importing my namespace at the beginning part of the page, as follows.
<%@ Import Namespace="utl=portal.library.Utilities" %>
And than in can use that on client side of the same asxp page like.
<script type="text/javascript">
var categoryPage;
categoryPage = '<%= utl.getcategoryName().ToString() %>';
</script>
My question is, can i use that '<%= utl.getcategoryName().ToString() %>' in an external javascript file ?
Is it possible something like that ?
<%@ Import Namespace="utl=portal.library.Utilities" %>
<script src="/scripts/trial.js" type="text/javascript"></script>
and in the trial.js file
var categoryPage;
categoryPage = '<%= utl.getcategoryName().ToString() %>';
thanks in advance..
I don't think so, because the external .JS file wouldn't be processed by ASP.NET and therefore wouldn't have access to those kinds of variables.
I don't think you can but you could instead try to pass the server side variable as a parameter to a JS function in the external JS file.
You can create a .aspx file that only outputs Javascript instead of HTML. As long as you set the Content Type to application/x-javascript
in the code behind, it will work.
For example, create Test.js.aspx. Then, in the code behind for Test.js.aspx.cs:
protected void Page_Load( object sender, EventArgs e )
{
Response.ContentType = "application/x-javascript";
}
protected string GetMessage()
{
return "Hello, World!";
}
In the Test.js.aspx file:
window.onload = function() {
var msg = <%=GetMessage() %>
alert(msg);
}
Now, it is true that the Javascript running on the client can't call C# functions running on the server. You would need AJAX for that. But you can certainly use this pattern to generate Javascript that make use of ASP.NET when it is generated.
精彩评论