Sending variable to a C# inside Javascript code - c#

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?

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.

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

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/

Related

Using server side PHP code from client side C#

I have a server side PHP script that looks like this
class MyObject {
function GetResult($input){
//some code
return $result;
}
}
I want to instantiate this object and call the GetResult function from client side c# application and get the get the result. How can i do so?
You can use Ajax call to hit on that PHP page and get the results from that PHP page.
Just use JQuery Ajax function like this and make object initialization in PHP page only.
$.ajax({
type: "POST",
url: "example.php",
data: {someParameter: "some value"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg)
{
}
});

Update markup dynamically after JS Ajax call to CodeBehind static function

I'm using $.ajax({...}); to send some data to my server (the aspx's CodeBehind file in c#). In order to receive this data to work with in the CodeBehind file, I have to use a static WebMethod ([System.Web.Services.WebMethod]). Once I work with this data, I want to either redirect them to a new page if there was a success (In my case, a successful credit card charge), otherwise, send an alert to the user that something went wrong (i.e., credit card charge randomly didn't work).
Is there a way to access/alter the current page's markup via this static WebMethod (e.g., add <script>alert("Something went wrong")</script>), without the ability to use asp page controls? (i.e., this which is the page in non-static methods in CodeBehind files)
You may need to use Success and Failure section of $.ajax syntax. Please refer an example below. I hope your web method returns string to make this work.
Sample WebMeethod
[ScriptMethod()]
[WebMethod]
public static string YourWebMethod()
{
String yourMessageString = String.Empty;
//process as per your logic
yourMessageString = "Some Message";
return yourMessageString;
}
$.ajax({
type: "POST",
url: "/yourpage.aspx/yourwebmethod",
async: false,
contentType: "application/json; charset=utf-8",
data: "your data",
dataType: "json",
success: function (message) {
alert(message);
},
error: function () {
alert("error");
},
failure: function () {
alert('failure');
}
});

passing a parameter from jQuery ajax call to C# method in web forms

I'm tring to pass a value I pull from a data-attribute in my markup to a C# method using jQuery Ajax. In this example, the value for QuestionNumber results in a 1. EMHQQuestion is an enum with values 1 through 15. I expect my C# method DeleteCondition to receive that 1 but instead I get a 500 internal server error: "Invalid web service call, missing value for parameter: 'questionNumber'.
Any suggestions?
function DeleteConditions() {
var QuestionNumber = $('.noRadioButton').data('questionnumber');
$.ajax({
url: "mhqpreinterview.aspx/deletecondition",
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
questionNumber: QuestionNumber
});
Dialog.dialog('close');
}
..
[WebMethod(EnableSession = true)]
public static void DeleteCondition(EMHQQuestion questionNumber)
{
//stuff
}
I struggled with this EXACT same thing when making AJAX reqs to web form methods.
For your c# method:
[System.Web.Services.WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string DeleteCondition(EMHQQuestion questionNumber)
{
// do enum stuff here
}
Please note that I have changed the method type from void to string. It is a good idea to send some identifiable information back to the client. Even if you do not have to send data back, it gives you a chance to customize success or helpful debugging information.
Here are the changes you have to make to your AJAX object:
var params = '{ questionNumber: ' + JSON.stringify(QuestionNumber) + '}';
var post = {
type: 'POST',
url: 'mhqpreinterview.aspx/deletecondition',
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json"
};
$.ajax(post);
What you should be taking away from the above javascript, is the use of JSON.stringify before you send to your method. You have to make sure QuestionNumber is parameterized correctly and already valid JSON for the web service method to receive.
If you find its still not working, check to see what value is being stored inside QuestionNumber before you are trying to send it.
The above code does work with me, any other troubles post a comment and I will do my best to help answer it.
Use data jquery ajax field:
data: JSON.stringify({QuestionNumber: QuestionNumber}),
dataType: "json",

How can I call a method that are in my code-behind via Javascript or Jquery

I have the follow line in my Javascript code
credenciadausuario = '<%= getCredenciada() %>';
In my code-behind I have this method
public string getCredenciada()
{
Utilidade.QuebraToken tk = new Utilidade.QuebraToken();
string credenciada = tk.CarregaToken(1, Request.Cookies["token"].Value);
return credenciada;
}
but when I put the debugger in my javascript code, the credenciadausuario variable, receives the string "<%= getCredenciada() %>" and not the return of my method. How can I call my method that are in my code-behind via javascript or jquery ?
It seems all you want to do in your code is get the value of a cookie. Why not do that in JavaScript on the client?
IF possible make use of ajax and do call the method, that will do you task.
check this post : http://pranayamr.blogspot.com/2012/01/calling-server-side-function-from.html
Cs File (codebehind)
[WebMethod]
public static string IsExists(string value)
{
//code to check uniqe value call to database to check this
return "True";
}
Javascript
function IsExists(pagePath, dataString)
{
$.ajax({
type:"POST",
url: pagePath,
data: dataString,
contentType:"application/json; charset=utf-8",
dataType:"json",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
},
success:
function(result) {
alert( result.d);
}
}
});}
var pagePath = window.location.pathname + "/IsExists";
var dataString = "{ 'value':'ab" }";
IsExists(pagePath, dataString);
This article from Encosia is excellent. It shows how to call a method in your code behind using jQuery ajax.
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
In your code behind you have to give the method the [WebMethod] attribute:
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
To call that method using jQuery you would use the following:
$.ajax({
type: "POST",
url: "PageName.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Well, to actually CALL your code-behind methods from Javascript, you would have to use ajax. JQuery has a nice $.ajax wrapper for that.
But I think you just want to include some value into the js code once, while it's being generated and sent to the browser. In that case, you need to use a file type which ASP.NET recognizes as a dynamic file.
The easiest would be to put JS code (in a <script> tag) into .ascx files. Then <%= getCredenciada() %> will be executed and will return an actual string which will be rendered into javascript code.
Then, of course, you should include such a control to the page as a regular ASP.NET control.
And I am not saying this is the best way to achieve what you want. Sometimes it's just the fastest.

Using jQuery AJAX to call ASP.NET function in control code-behind instead of page code-behind

I have a user control that I'm creating that is using some AJAX in jQuery.
I need to call a function in the code-behind of my control, but every example I find online looks like this:
$("input").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetResult",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
//do something
}
});
});
This works fine if I have the method in the Default.aspx page. But I don't want to have the function there, I need the function in the code-behind of my control. How can I modify the url property to call the correct function?
I tried:
url: "GetResult"
but that didn't work.
The way to handle this is to have the webmethod in your page, then just pass the values directly to a control method with the same signature in your control - there is no other way to do this.
In other words, ALL the page method does is call the usercontrol method so it is really small. IF you have the same signature for multiple child controls, you could pass a parameter to tell the page method which one to call/use.
EDIT: Per request (very very simple example). You can find other examples with more complex types being passed to the server side method. for instance see my answer here: Jquery .ajax async postback on C# UserControl
Example:
Page method: note the "static" part.
[WebMethod]
public static string GetServerTimeString()
{
return MyNamespace.UserControls.Menu.ucHelloWorld();
}
User Control Method:
public static string ucHelloWorld()
{
return "howdy from myUserControl.cs at: " + DateTime.Now.ToString();
}
Client ajax via jquery:
$(document).ready(function()
{
/***************************************/
function testLoadTime(jdata)
{
$("#timeResult").text(jdata);
};
$("#testTimeServerButton").click(function()
{
//alert("beep");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "MyPage.aspx/GetServerTimeString",
success: function(msg)
{
testLoadTime(msg);
}
});
});
});
Note: the dataFilter: function(data)... part of the ajax is so that it works with 2.0 and 3.5 asp.net ajax without changing the client code.
You can't...WebMethods have to be in WebServices or Pages, they cannot be inside UserControls.
Think about it a different way to see the issue a bit clearer...what's the URL to a UserControl? Since there's no way to access them you can't get at the method directly. You could try another way perhaps, maybe a proxy method in your page?

Categories

Resources