Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use "<%= someObject.ClientID %>" in an external javascript file?

Is there a way to use "<%= someObject.ClientID %>" in an external javascript file?

If I use the code

<%= someObject.ClientID %> 

in a script tag inside my as(c/p)x page, it works fine. On the rendered page, the ClientID is resolved. Howvever, if I put in an external JS file and just add:

It doesn't. Is there a way to do this or am I stuck with leaving that code in the as(c/p)x file?

Side question -- what is the act of doing <%=... %> in your markup file called?

like image 554
Matt Avatar asked Jun 30 '11 23:06

Matt


People also ask

How do you call a function in an external JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Can external scripts contain script tags?

External scripts cannot contain <script> tags.

What is more appropriate way to include JavaScript as an external file?

Create external JavaScript file with the extension . js. After creating, add it to the HTML file in the script tag. The src attribute is used to include that external JavaScript file.

Does external JavaScript need script tag?

External Javascript should not contain tag. Show activity on this post. No, <script> tags are not needed otherwise error occurs. For example, external.


2 Answers

If you really want to do this you can do following

<%@ Page ContentType="text/javascript" Language="C#" AutoEventWireup="false" %> <%@ OutputCache Duration="86400" Location="Any" VaryByParam="None" %>  var time = "<%= DateTime.Now.ToString() %>"; alert(time); 

And then reference it in your page

<script src="Scripts/file.aspx" type="text/javascript"></script> 

Note When using mentioned method, the only way to pass target page controls client-ids, is to store client id as string in a public property, and then reference it using new instance of that page

If the only thing that made you to do this is client-id then you can use following ASP.NET 4 feature

<any-tag ID="myCustomId" runat="server" ClientIDMode="Static" /> 

You can also put all your client-ids in C# class then serialize it using JSON and render it in script tag, could be smart way for ASP.NET prior to version 4.

Note using serialization method you have possibility to change any tag ids without worrying about javascript element usages, remember that this is not even possible with ASP.NET 4 ClientIDMode

See

Page-Code-File

public partial class About : System.Web.UI.Page {     ...      protected string GetTagIds()     {         return new JavaScriptSerializer()                     .Serialize(new                      {                             myButton = Button1.ClientID,                             myCalendar = Calendar1.ClientID                      });     }       ... } 

Page-ASPX

<script type="text/javascript">     var IDs = <%= GetTagIds() %>; </script> 

Anywhere

<script type="text/javascript">     IDs.myCalendar.doSomthing... </script> 

There is another option that you can pass all javascript files to ASP.NET handler but i don't recommend it, because of just a single javascript file you make asp.net handler busy.

Code Blocks

<% inline code %>

This is an inline code definition which you can execute codes in it :

<% Response.Write("Hi"); %>  <% while(i < 0) { %>       <%           Response.Write(i.ToString());           i++;       %> <%}%> 

Note You have to include ';' on end of each statement when using inline code with C# language, you can change inline language using page directive language attribute

<%= inline expression %>

This one equals to calling Response.Write your self, see:

<%= "Hi" %> equals to <% Response.Write("Hi"); %> 

Note You shouldn't include ';' when using inline expression

<%: encoded inline expression %>

This one equals to :

Response.Write(HttpUtility.HtmlEncode("<script type="text/javascript">alert('XSS');</script>")) 

And is used for security reasons --XSS, any input HTML to this one outputs HTML encoded text which is safe to display user entered contents in page.

Note You shouldn't include ';' when using encoded inline expression

<%$ expressionPrefix: expressionField %>

This one is expression that you can use to bind values from ConnectionStrings, Resources and AppSettings

expressionPrefix possibilities is

  • AppSettings
  • ConnectionStrings
  • Resources

expressionField is the property of specified expressionPrefix that you need, see:

// AppSettings <asp:Label ... Text="<%$ AppSettings: version %>" />  // ConnectionStrings <asp:SqlDataSource ... ConnectionString="<%$ ConnectionStrings:dbConnectionString %>" />  // Resources <asp:Label ... Text="<%$ Resources: Messages, Welcome %>" /> 

Note You shouldn't include ';' and you can use expressions only on ASP.Net controls attributes

<%# data-binding expression %>

You can use this anywhere inside controls with data-binding support, and usually is used by Eval and Bind methods.

<asp:DropDownList SelectedValue='<%# Bind("CategoryID") %>'                    DataSourceID="CategoriesDataSource"                   DataTextField="CategoryName"                   DataValueField="CategoryID"                   runat="Server" /> 

Which one Eval or Bind?

Using Bind you have two-way binding set over specified attribute of ASP.NET control see the mentioned drop-down, it is using Bind that means if end-user selects a value and then submit the page, drop-down will not loose its selected value.

Use Eval just for displaying data.

<asp:FormView ...>      <ItemTemplate>           <a href='Eval("Link")'>Eval("LinkText")</a>      </ItemTemplate> </asp:FormView> 

<%@ text template directive %>

<%@ Page ...%> This one is Page Directive  <%@ OutputCache...%> This one is OutputCache Directive and so on... 
like image 102
Beygi Avatar answered Sep 21 '22 10:09

Beygi


This is totally possible.

In your .aspx page, create a script reference to an aspx page that contains your javascript code:

<script src="../MyJavaScriptFile.js.aspx" type='text/javascript'></script> 

Then, in MyJavaScriptFile.js.aspx you can write the following:

<%@ Page Language="C#" AutoEventWireup="false"  ContentType="text/javascript" %>  <%      var foo = new Whatever();     foo.ClientId = 123; %>  // Start Javascript var clientId = <% HttpContext.Current.Response.Write(foo.ClientId); %>; 

.

Also helpful - this technique supports querystring parameters:

 <script src="../MyJavaScriptFile.js.aspx?username=<% somevalue %>"         type='text/javascript'></script> 

Then, in MyJavaScriptFile.js.aspx, I can reference the value with

var username = '<% Request.QueryString["username"] %>'; 

It's not the "best practice" way to do things, but it gets the job done in a way that my caveman brain can understand without resorting to fancy workarounds.

like image 28
Daniel Szabo Avatar answered Sep 19 '22 10:09

Daniel Szabo