最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asp.net - Check for IsPostBack in external Javascript file - Stack Overflow

programmeradmin2浏览0评论

From an extrnal Javascript file, I need to check for IsPostBack (ASP.NET page). Here is what I found after googling:

var isPostBack = <%= Page.IsPostBack ? "true" : "false" %>;

But <%= %> doesn't seem to be recognized in the external JS file. If so, what is the alternate solution?

From an extrnal Javascript file, I need to check for IsPostBack (ASP.NET page). Here is what I found after googling:

var isPostBack = <%= Page.IsPostBack ? "true" : "false" %>;

But <%= %> doesn't seem to be recognized in the external JS file. If so, what is the alternate solution?

Share Improve this question edited Feb 3, 2012 at 21:30 Jon Adams 25.2k18 gold badges84 silver badges121 bronze badges asked Feb 3, 2012 at 20:03 BumbleBeeBumbleBee 10.9k20 gold badges80 silver badges124 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 3

You won't be able to do that from an external file. Even if you could, external files get cached on the client's browser, and they don't get pulled every time. You might be able to place a function in the page and call it from the external script.

External Script

if(isAPostBack)
{
//run code
}

ASPX Page (Script in header)

var isAPostBack = <%= Page.IsPostBack %>;

Just make sure that your external script gets loaded after the above line in the page.

For ASP code to be processed you need to have a file extension which is mapped to the ASP dll in IIS.

The simplest case here would be to rename your .js file with a .aspx extension, then change the src attribute of your <script> element.

Alternatively, create your isPostBack variable globally in your aspx page, and then call your js file which contains its usage, eg:

<script type="text/javascript">
    var isPostBack = <%= Page.IsPostBack ? "true" : "false" %>;
</script>
<script type="text/javascript" src="/js/myscript.js"></script> <!-- <- script that uses isPostBack -->

You cannot use <%= %> notation in an external JavaScript file; it will not work.

This will not work in a Javascript file cause the Server will serve it as such and wont recognize the asp tags. You could do this, however, from a aspx file and it will work. You could also use a Generic Handler.

Good luck!

You can only render this variable through the aspx page or user control or master page used on the page.

发布评论

评论列表(0)

  1. 暂无评论