Sora
Sora

Reputation: 2551

calling a server side function from javascript without using ajax

I am trying to do the following :

function redirectContactOnClick(contactId) {
            var enc=<%= QueryStringModule.Encrypt("cont="+ contactId)%>;
            alert(enc);
            //window.location = "Contacts/AddEditContact.aspx";
        }

QueryStringModule.Encrypt is a function inside a c# class, the page raise an error saying :The name 'contactId' does not exist in the current context

Upvotes: 0

Views: 3521

Answers (3)

akhil_jose
akhil_jose

Reputation: 19

You can call Server side(C#) function from javascript. First you have include your script inside a ScriptManager runnable at server. Then the javascript function can call the c# function (which is having an attribute of ([System.Web.Services.WebMethod] and must be static) can be accessed.

eg.

 PageMethods.QueryStringModule.Encrypt("cont="+ contactId);

on client-side, and

  [System.Web.Services.WebMethod]
  public static void Encrypt(string id)
  {
       // Do something
  };

on server-side

(Source: http://www.codeproject.com/Questions/727256/how-to-call-server-side-function-from-javascript)

Upvotes: 1

Fabio
Fabio

Reputation: 1960

For to call the Server Side member the only mode is do a request HTTP or sync (POST Page) o async (AJAX)

you don't call a server function directly

in the you case

receive an error because contactId not is an page's member you can comunicate with these way

ASP.NET Client to Server communication

Upvotes: 0

Vladimirs
Vladimirs

Reputation: 8599

You won't be able to pass your javascript variable (contactId) to C# method. Suggest to look a different solution for that, for example, making Generic Web Handler (.ashx) and pass there your contactId via ajax and get back whatever you expect from your Encrypt call.

Upvotes: 1

Related Questions