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

javascript - For Loop With C# Code Behind Method - Stack Overflow

programmeradmin0浏览0评论

When I debug in code behind It let me to go inside "Test" method only one time, not three times, why ? I see that I have javascript "for loop" which should go three times inside C# "Test" method. But it goes only one time, is this normal ? I want to go through "Test" method three times as I said in javascript "for loop". Where is the problem ?

aspx code:

<script>
    $(function () {
        for (var i = 0; i < 3; i++) {

            console.log("active");
            var a = '<%= this.Test() %>';
        }
    });
</script>

C# code behind:

    public string Test()
    {
        int a = 1;
        return "active";
    }

When I debug in code behind It let me to go inside "Test" method only one time, not three times, why ? I see that I have javascript "for loop" which should go three times inside C# "Test" method. But it goes only one time, is this normal ? I want to go through "Test" method three times as I said in javascript "for loop". Where is the problem ?

aspx code:

<script>
    $(function () {
        for (var i = 0; i < 3; i++) {

            console.log("active");
            var a = '<%= this.Test() %>';
        }
    });
</script>

C# code behind:

    public string Test()
    {
        int a = 1;
        return "active";
    }
Share Improve this question asked Feb 20, 2013 at 14:33 TheChamppTheChampp 1,4375 gold badges25 silver badges41 bronze badges 1
  • 1 What are you basing the "only 1 time" on? Cause it looks like it'll run 3 times, but a will always be 1. – PiousVenom Commented Feb 20, 2013 at 14:35
Add a ment  | 

3 Answers 3

Reset to default 8

this.Test() is not being called in your for loop in javascript. It is being called server-side to evaluate it.

Look at it this way. Your javascript really says the following after rendering:

<script>
    $(function () {
        for (var i = 0; i < 3; i++) {

            console.log("active");
            var a = 'active';
        }
    });
</script>

The reason for this is in the way ASP.NET works. It takes your xhtml and server-side code and renders html to spit back to the client. The client then has a chance to execute any of its code. Javascript is executed client-side.

You are writing the result of the Test function as a string into the javascript, which will then execute once the browser loads the page.

If you want to run Test 3 times from the page itself, you'll want to look into one of the various Ajax libraries.

The code only executes once in all cases. The for loop on the JavaScript will not execute the c# 3 times. Instead, the page is output only once as the <%= this.Test() %> is an output block that is interpreted a single time on the server. Your script clientside is then interpreted.

发布评论

评论列表(0)

  1. 暂无评论