有没有办法使用“<%= someObject.ClientID %>”在外部 javascript 文件中?

发布于 2024-11-18 03:10:43 字数 338 浏览 5 评论 0原文

有没有办法使用“<%= someObject.ClientID %>”在外部 javascript 文件中?

使用该代码

<%= someObject.ClientID %>

如果我在 as(c/p)x 页面内的脚本标记中 ,则它可以正常工作。在渲染的页面上,ClientID 被解析。 但是,如果我放入外部 JS 文件并添加:

事实并非如此。有没有办法做到这一点,或者我是否坚持将该代码留在 as(c/p)x 文件中?

附带问题——<%=... %> 的行为是什么?在你的标记文件中调用?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

天生の放荡 2024-11-25 03:10:43

如果您确实想这样做,您可以执行以下操作

<%@ Page ContentType="text/javascript" Language="C#" AutoEventWireup="false" %>
<%@ OutputCache Duration="86400" Location="Any" VaryByParam="None" %>

var time = "<%= DateTime.Now.ToString() %>";
alert(time);

,然后在您的页面中引用它

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

注意使用上述方法时,传递目标页面控件客户端 ID 的唯一方法是将客户端 ID 作为字符串存储在公共属性中,然后使用新实例引用它该页面的

如果唯一让您这样做的是客户端 ID,那么您可以使用以下 ASP.NET 4 功能

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

您还可以将所有客户端 ID 放入 C# 类中,然后使用 JSON 序列化它并在脚本中呈现它标签,对于 ASP.NET 之前的版本来说可能是明智的方式4.

注意使用序列化方法,您可以更改任何标记 ID,而不必担心 javascript 元素的使用,请记住,这在 ASP.NET 中甚至是不可能的4 ClientID模式

可见

页面-代码-文件

public partial class About : System.Web.UI.Page
{
    ...

    protected string GetTagIds()
    {
        return new JavaScriptSerializer()
                    .Serialize(new
                     {
                            myButton = Button1.ClientID,
                            myCalendar = Calendar1.ClientID
                     });
    } 

    ...
}

页面-ASPX

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

随处

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

还有另一个选项,您可以将所有 javascript 文件传递​​给 ASP.NET 处理程序,但我不推荐它,因为您只创建一个 javascript 文件 ASP.NET 处理程序忙碌的。

代码块

<%内联代码%>

这是一个内联代码定义,您可以在其中执行代码:

<% Response.Write("Hi"); %>

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

注意您必须包含“;”在 C# 语言中使用内联代码时,可以在每个语句的末尾使用页面指令语言属性更改内联语言

<%= 内联表达式 %>

这相当于调用 Response.Write your self,看:

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

注意您不应包含“;”使用内联表达式时

<%: 编码的内联表达式 %>

这一个等于:

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

并且出于安全原因使用--XSS,任何输入 HTML 到此输出HTML 编码文本可以安全地在页面中显示用户输入的内容。

注意您不应包含“;”使用编码内联表达式时

<%$ expressionPrefix: expressionField %>

这是一个表达式,您可以使用它来绑定来自 ConnectionStrings、Resources 和 AppSettings 的值。

expressionPrefix 的可能性是

  • AppSettings
  • ConnectionStrings
  • Resources

expressionField 是指定您需要的表达式前缀,请参阅:

// AppSettings
<asp:Label ... Text="<%$ AppSettings: version %>" />

// ConnectionStrings
<asp:SqlDataSource ... ConnectionString="<%$ ConnectionStrings:dbConnectionString %>" />

// Resources
<asp:Label ... Text="<%$ Resources: Messages, Welcome %>" />

注意您不应包含“;”并且只能在 ASP.Net 控件属性上使用表达式

<%# data-bounding expression %>

您可以在具有数据绑定支持的控件内的任何位置使用此表达式,通常由 Eval 和绑定方法。

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

Eval 或 Bind 哪一个?

使用 Bind,您可以在 ASP.NET 控件的指定属性上设置双向绑定,请参阅提到的下拉列表,使用 Bind 意味着如果最终用户选择一个值然后提交页面,下拉列表将不会丢失其值选定的值。

使用 Eval 仅用于显示数据。

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

<%@ 文本模板指令 %>

<%@ Page ...%>
This one is Page Directive

<%@ OutputCache...%>
This one is OutputCache Directive and so on...

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...
还如梦归 2024-11-25 03:10:43

这是完全有可能的。

在您的 .aspx 页面中,创建对包含 javascript 代码的 aspx 页面 的脚本引用:

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

然后,在 MyJavaScriptFile.js.aspx 中您可以编写以下内容:

<%@ 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); %>;

也很有帮助 - 这项技术支持查询字符串参数:

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

然后,在 MyJavaScriptFile.js.aspx 中,我可以引用该值,

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

这不是做事的“最佳实践”方式,但它以我的穴居人大脑可以完成的方式完成工作无需诉诸花哨的解决方法即可理解。

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.

陌伤浅笑 2024-11-25 03:10:43

我喜欢在我的页面上嵌入一行 JavaScript。

<script type="text/javascript">
   Application.init({variable1: "value1", variable2: "value2"...});
</script>

在页面上呈现大量 JavaScript 是一种不好的做法,但通常需要从服务器将初始化值传递给 JavaScript。这允许您在没有一大堆不必要的代码的情况下完成此操作,并且不会用回调函数污染全局名称空间。我通常用一些项目特定的全局包装器替换 Application

I like to embed a single line of javascript on my page.

<script type="text/javascript">
   Application.init({variable1: "value1", variable2: "value2"...});
</script>

It's poor practice to have a ton of javascript rendered on your page, but it is common to need to pass initialization values to your javascript from the server. This allows you to do it without a whole bunch of unnecessary code and without polluting the global namespace with callback functions. I usually replace Application with some project specific global wrapper.

千纸鹤 2024-11-25 03:10:43

这会添加更多的 HTML,但它可以工作;将每个服务器控件包装在一个div中...

<div id="myContainer">
    <asp:HiddenField ID="hdMyControl" runat="server" /></div>

在后面的代码中设置HiddenField的值

hdMyControl.Value = "something";

然后在您的外部JS文件中您可以获取服务器控件的值

$(document).ready(function () {
    var myValue= $('#myContainer input[type=hidden]').val();

我不确定这是否重要,但我将脚本引用添加到使用 RegisterClientScriptBlock 通过代码隐藏进行页面

This adds a bit more HTML but it works; wrap each server control in a div...

<div id="myContainer">
    <asp:HiddenField ID="hdMyControl" runat="server" /></div>

Set the HiddenField's value in the code behind

hdMyControl.Value = "something";

Then in your external JS file you can get the server control's value

$(document).ready(function () {
    var myValue= $('#myContainer input[type=hidden]').val();

I'm not sure that it matters, but I'm adding the script reference to the page via the codebehind using RegisterClientScriptBlock

污味仙女 2024-11-25 03:10:43

您可以在外部文件中创建一个空的回调函数:

var MyCallback = function () { };

然后在 asp/cx 中执行以下操作:

MyCallback = function () {return "<%= someObject.ClientID %>";}

然后,回到外部文件中:

var myClientID = MyCallback();

You could create an empty callback function in the external file:

var MyCallback = function () { };

And then in the asp/cx do something like:

MyCallback = function () {return "<%= someObject.ClientID %>";}

And then, back in your external file:

var myClientID = MyCallback();
永言不败 2024-11-25 03:10:43

不,它不会那样工作,因为 javascript 文件作为单独的文件独立传输,并且在输出时不会被 ASP.NET 解析,而您的 aspx 文件正在被解析并且 .NET 引擎正在替换带有实际值的标签。

现在,当您的对象调用这些 JS 函数时,它们可以做的就是将对自身的引用传递到函数中,甚至传递某种字典列表,其中包含您自己的控件的键和分配的名称。

还需要考虑一件事 - 如果您要创建一个独立于 ASPX 页面的 JS 文件,那么该 JS 文件绝对不应该假定知道有关 aspx 文件的特定控件的任何信息调用它 - 因为稍后其他人可能会决定,“哦,这是一个很好的 JS 文件,我也将合并它”,并且它对他们不起作用,因为他们的对象与你的对象不匹配。因此,您应该遵循的模式必须更加通用 - 这就是为什么您想要传递引用或标识符列表。

No, it won't work like that because the javascript file is being transmitted independently as a separate file and it isn't parsed by ASP.NET on the way out, while your aspx file IS being parsed and the .NET engine is replacing the tag w/ the actual value.

Now when your objects call those JS functions, what they could do is pass references to themselves into the function, or even pass in a dictionary list of some sort with your own key for what the control is and the assigned name.

One thing to think about as well - IF you are going to make a JS file independent of an ASPX page, then that JS file absolutely should not presume to know anything about the specific controls of the aspx file that calls it - because later on someone else might decide, "Oh that's a good JS file, I'll incorporate it too" and it won't work for them cause their objects wont match yours. Thus the pattern you should follow would have to be more generic - thus why you'd want to pass in references or lists of identifiers.

挽清梦 2024-11-25 03:10:43

服务器标记 <%= %> 用于输入在服务器上处理的代码。

您不能在外部js文件中使用<%= someObject.ClientID %>,因为服务器标记是asp.net的东西,而js不知道这是什么。

如果您使用 ASP.NET 4,您可以在控件的属性中设置客户端 ID,使其可预测。

如果您不使用 ASP.NET 4,您可以将此客户端 ID 放入隐藏字段或内联 js 变量中。

The server tag <%= %> is used to enter code that is processed on the server.

You cannot use <%= someObject.ClientID %> in an external js file because the server tag is an asp.net thing and js doesn't know what this is.

If you use ASP.NET 4 you can set the client id in the properties of the control making it predictable.

If you don't use ASP.NET 4 you could put this client id in a hidden field or an inline js variable.

帅冕 2024-11-25 03:10:43

在脚本源文件中使用标准前缀标识符:

document.getElementById("ctl00_ContentDetail_textboxelename").value = "";
document.getElementById("ctl00_ContentDetail_radioORcheckboxelename").checked = false;
document.getElementById("ctl00_ContentDetail_elename").style.visibility = "hidden";
var javaele = document.getElementById("ctl00_ContentDetail_elename");
var boolIsChecked = document.getElementById("ctl00_ContentDetail_radioORcheckboxelename").checked;

Use the standard prefix identifier in script source files:

document.getElementById("ctl00_ContentDetail_textboxelename").value = "";
document.getElementById("ctl00_ContentDetail_radioORcheckboxelename").checked = false;
document.getElementById("ctl00_ContentDetail_elename").style.visibility = "hidden";
var javaele = document.getElementById("ctl00_ContentDetail_elename");
var boolIsChecked = document.getElementById("ctl00_ContentDetail_radioORcheckboxelename").checked;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文