开发者

Possible to get an ASP.NET control value from inside of an javascript file?

I would like to get the value of an ASP.NET control from inside of a javascript file. I know how to do this when the javascript is on the aspx page, but not when it is in a js file. Example:

<head>
    <script type="text/javascript">
        alert('<%= lbl_test.Text %&g开发者_C百科t;'); //alerts the text of the ASP.NET label
    </script>

    <script type="text/javascript" src="Scripts/test.js" /> //alerts "<%= lbl_test.Text" %>
</head>

In this example test.js only has alert('<%= lbl_test.Text %>'); in it.

Is there anyway for me to reproduce the behavior in the first piece of javascript in the js file?


You cannot do it like this you will have to either

  1. pass in the control id from an aspx page (some . net page) that calls into the function in your javascript file

or

  1. make your script file actually a .net output file. Then you can embed your code. name it for example javscriptwhatever.aspx but set the content type of the file in the code behind to be text/javascript as described here for example http://social.msdn.microsoft.com/Forums/en-US/jscript/thread/c706d380-9688-4758-9d7e-9522d59d5855


As a further suggestion to what @Adam provides, you might consider using the #include directive. Using this method you can ought to be able to wrap the code of your .js file within the appropriate <script> tag and 'inject' it via an #include reference:

<head>
    <!--#include file="myScript.js"-->
</head>

I've not tested this, and it is simply another possibility. I don't and won't necessarily advocate actually using #includes on a regular basis, and would avoid them in most cases; but if your options are slim, it might work out.

I think your best bet is the first suggestion of modifying the script to accept any arguments required to do this from the native language, avoiding the mix of inline ASP.NET script and Javascript.


The page that ASP.NET outputs to a web browser is, by necessity, standard HTML/Javascript/CSS. The Javascript runs on the client side on the web browser. So it is possible to do anything with the Javascript that you can do normally on the client.

A label will output as a span. So you can do something like this:

function getLabelValue(lbl) {
    if ( lbl.childNodes.length == 0 )
        return null;

    var textValue = "";
    for ( var i = 0; i < lbl.childNodes.length; i++ )
    {
        if ( lbl.childNodes[0].nodeType == Node.TEXT_NODE )
            textValue += lbl.childNodes[0].nodeValue;
    }

    return textValue;
}

var lbl = document.getElementById("lbl_test");
var value = getLabelValue(lbl);
alert(value);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜