Click here to Skip to main content
15,912,504 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
How do I... call the instance method from javascript method

i want to call the instance method in C# based on condition in javascript
Posted
Comments
Arjsrya 29-Dec-14 5:09am    
Did you try web service?you can expose those methods and call them from the jquery ajax.

You never call any C# methods from Javascript. This question demonstrate lack of understanding of the Web operation. These methods are on the server side, and Javascript works on the client side.

But you can send HTTP request to the server side and receive HTTP response. Of course, on the server side you should have some code designed to handle such requests. You can use Ajax: http://en.wikipedia.org/wiki/Ajax_(programming)[^].

One convenient way of doing it would be using jQuery Ajax: http://api.jquery.com/jquery.ajax[^].

—SA
 
Share this answer
 
Comments
Maciej Los 29-Dec-14 3:28am    
+5!
Sergey Alexandrovich Kryukov 29-Dec-14 3:32am    
Thank you, Maciej.
—SA
In addition to Solution 1 by Sergey Alexandrovich Kryukov[^], i'd suggest to read this: Create Advanced Web Applications With Object-Oriented Techniques[^]. Author explains the differences between C# instances of classes/structs and JavaScript objects.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 29-Dec-14 3:32am    
It looks useful, a 5.
—SA
Maciej Los 29-Dec-14 3:39am    
Thank you, Sergey ;)
Use ajax call for achieving your requirement
in javascript code set a parameter value based on condition and then pass that value to your c# code using ajax
eg.

function myfunc()
{
var url = "/Yourajaxfile.aspx?MethodName=" + value;
$.ajax({
type: "POST",
url: url,
success: function (msg) {


},
Error: function (x, e) {
alert("Error Occured");
}
});
}

then in page load of c# file read value of parameter using querystring and then call methods using if else based on parameter
 
Share this answer
 
v2
You can call an instance method with Javascript like following.

JavaScript
<script>
		function CodeBehindMethod(var conditionValue) {
                    if(conditionValue==true)
			alert('<%= GetFirstValue() %>');
                    else
                        alert('<%= GetSecondValue() %>');
		}
	</script>



Code Behind will look like --

C#
public String GetFirstValue()
	{
		return "FirstValue";
	}
public String GetSecondValue()
	{
		return "SecondValue";
	}


In case, I am wrong somewhere, please let me know :)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900