MaxCoder88
MaxCoder88

Reputation: 2428

Sending variable to a C# inside Javascript code

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?

Upvotes: 0

Views: 173

Answers (3)

hungryMind
hungryMind

Reputation: 7009

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/

Upvotes: 0

MikeM
MikeM

Reputation: 27415

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);
        }
    });
}

Upvotes: 0

epascarello
epascarello

Reputation: 207557

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.

Upvotes: 4

Related Questions