0

Javascript Code:

function jsfunction ()
{
var sayi = 9999;
alert('<%= cfunction("'+sayi+'")%>');
} 

C# Code:

public string cfunction(string gelen)
{
 return gelen;
} 

Normally,There is should be 9999 value which is send to C# code from javascript code,but,this value returning as '+sayi+'. Also,that's gives me alert 9999.What am I wrong?

1
  • 2
    You are misunderstanding several things, but first of all, you code should not even compile. You are declaring the sayi variable in javascript, and consuming it in C# (between the <%= and %>). That is not possible, so where is sayi declared such that the C# code can see it? Commented Jul 26, 2011 at 17:47

3 Answers 3

4

By the time JavaScript runs, the C# code has already been executed. Learn you page life cycle.

If you want to call a serverside function to get data, you need to learn about Ajax.

Sign up to request clarification or add additional context in comments.

Comments

0

C# (server-side) can generate markup for client side, client side can't call back up to server-side without some kind of Ajax type web request.

To do what you're looking for you can create a C# webmethod

[WebMethod()]
public static string cfunction(string gelen)
{
    return gelen;
}

And consume the webmethod with a client-side jQuery.ajax() method (You'll need the jQuery library script if you don't have it already)

function jsfunction() {
    var sayi = 9999;
    $.ajax({
        type: "POST",
        url: "YOUR-ASPX-PAGE.aspx/cfunction",
        data: "{gelen:'" + sayi + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            alert(msg.d);
        }
    });
}

Comments

0

You can use scriptmethod attribute to invoke server side method from your javascript code. But you must understand the mechanism behind it so that u can debug and modify accordingly.

http://www.chadscharf.com/index.php/2009/11/creating-a-page-method-scriptmethod-within-an-ascx-user-control-using-ajax-json-base-classes-and-reflection/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.