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

c# - Calling Javascript function from Code behind page - Stack Overflow

programmeradmin0浏览0评论

I have a script that I want to pop a window after 5 page views. The java script works fine on the default.aspx page with a link to call it. But I want to launce it from my default.aspx.cs page after my session var count gets to 5. How can I do this? Is it possible?

default.aspx

  <script type="text/javascript">
    window.name = "Register";
    function popWin(link) {
        var w = window.open(link.href, link.target, 'width=500,height=600,resizable');
        return w ? false : true; // if popup blocker, use the default behaviour of the link 
    } 
</script>

Default.aspx.cs page

 if (Session["PagesViewed"].ToString() == "5")
            {
              //Call my Javascript function How?????

            }

I have a script that I want to pop a window after 5 page views. The java script works fine on the default.aspx page with a link to call it. But I want to launce it from my default.aspx.cs page after my session var count gets to 5. How can I do this? Is it possible?

default.aspx

  <script type="text/javascript">
    window.name = "Register";
    function popWin(link) {
        var w = window.open(link.href, link.target, 'width=500,height=600,resizable');
        return w ? false : true; // if popup blocker, use the default behaviour of the link 
    } 
</script>

Default.aspx.cs page

 if (Session["PagesViewed"].ToString() == "5")
            {
              //Call my Javascript function How?????

            }
Share Improve this question asked Dec 31, 2011 at 19:54 CsharpBeginnerCsharpBeginner 1,7738 gold badges40 silver badges68 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

You can output javascript into a LiteralControl from your code behind:

.aspx:

<asp:Literal id="myLiteral" runat="server" />

Code behind:

myLiteral.Text = "<script type='text/javascript'>popWin('url');</script>";

When rendered this way, the output script will call the function - make sure it is lower in the page than where the function was defined to ensure it exists.

In ASP.Net you can do the following:

Page.ClientScript.RegisterStartupScript(
    this.GetType(),
    "openpopup",
    "popWin('www.someurl.');",
    True);

If you need more control over your scripts placement @Oded has a better approach - as trying to call a function that has not been defined isn't a good idea...

You cannot call javascript functions directly from C#. However, what you could do is pass a <script> to the browser that executes the function.

response.Write("<script>popWin(something);</script>");
发布评论

评论列表(0)

  1. 暂无评论