WebMethod Error - c#

I am getting "NetworkError: 500 Internal Server Error - http://localhost:5963/default.aspx/Call" when am calling this server side function using jquery
<html>
<head>
<script src="scripts/jquery-1.2.6-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function () {
$.ajax({
type: "POST",`enter code here`
url: "default.aspx/Call",
data: "{}",
contentType: "application/json; charset=utf-8",
async: true,
dataType: "json",
success: function (msg) {
alert("sdsd");
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:RadioButton runat="server" ID="btn" Text="A" />
</form>
</body>
</html>
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static void Call(string value)
{
var x = value;
}

First of all this script won't return anything because you're using the wrong id of a server control. When a server control is rendered, it's id changes.
Try using :
$("#<%=btn.ClientID %>")
You have another problem. You're calling an overloaded web method, so you need to pass some data :
data: "{'value': 'somevalue'}",
Hope this will help.

Does this path scripts/jquery-1.2.6-vsdoc.js give you proper jQuery file? It looks like you're trying to load vsdoc file as a normal library.

The first thing you need to do is use the FireBug console. That will tell you what the error is.
But your code won't work because your return type is void. You actually need to return something back to the client. Change it to this:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string Call(string value)
{
var x = value;
return x; // Silly example
}

Related

passing bulk array values to codebehind(cs) using ajax

I have to pass bulk array values to code behind (cs) using ajax i had researched a lot and used this code but it didnot worked for me below is the code that i used what i need is i need to pass bulk array values in code behind(cs) using ajax
JS
<head runat="server">
<title></title>
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
</body>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace PassingValueFromJavascriptToCs
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void done(string[] ids)
{
String[] a = ids;
// Do whatever processing you want
// However, you cannot access server controls
// in a static web method.
}
}
}
First of all the button for aspx is sending your aspx form to a postback so that you would need to change the aspx like this
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
</body>
The reason the foo method returns false that you dont want to make your button start a postback. I also added another property UseSubmitBehavior="false" to guarantee it.
The scripts section i changed the values object to a real array and then when sending data , i converted it to json with values object inside. This code will work in your example just fine
Edit : For the working version on my tests
The aspx page (trimmed details to the master page)
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script>
function test() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/test", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
debugger;
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
<asp:Button ID="Button3" UseSubmitBehavior="false" OnClientClick="return test();" runat="server" Text="Deneme" />
</asp:Content>
The RouteConfig and original method
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
//settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
[WebMethod]
public static void test(string[] arr)
{
}
Well at least one issue is your url is "Default.aspx/Done" but the method appears to be on WebForm3.aspx/Done.
What actually happens with your code? Does it error?

Getting error 500 while using Ajax call in ASP.NET Webforms

I am trying to call a simple void in html page but it shows error 500.
Can anyone help me i'm getting crazy!
In console log shows this error :
POST http://localhost:15041/Default.aspx/SaveUser 500 (Internal Server Error)
my html code :
<head runat="server">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True"></asp:ScriptManager>
</form>
<script>
$.ajax({
type: "POST",
url: "/Default.aspx/SaveUser",
data: "{id:'1'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("SUCCESS: " + msg.d);
},
error: function (err) {
alert("FAILURE");
}
});
</script>
</body>
and here is my C# code :
[WebMethod]
[ScriptMethod]
public static int SaveUser(int param)
{
return 10;
}
As #Zaki commented, that was my mistake, I should change data part of ajax to :
data:"{param:'1'}"

jquery ajax method in asp net without using webmethod

Aspx Page
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#Content").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
});
</script>
</head>
<body>
<form id="frm" method="post">
<div id="Content">
</div>
</form>
</body>
</html>
Code behind
public static string GetData()
{
return "This string is from Code behind";
}
I want to get this function using ajax without using "WEBMETHOD". i.e. GetData() method, I want to show in my .aspx page without using web service.
i'm not sure i get your question but maybe what you are looking for is simply the code you need in the onload event of the page:
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/json";
Response.Write("put a valid json string here");
}

Call asp.net function from javascript function

I want to call asp.net function from a javascript function passing string value.
this is the asp.net function :
[System.Web.Services.WebMethod]
public static string InsertData(string ID)
{
string source = "Data Source=(LocalDB)\v11.0;Integrated Security=True;Connect Timeout=30";
using(SqlConnection con = new SqlConnection(source))
{
using (SqlCommand cmd = new SqlCommand("Insert into Book (Name) values(#Name)", con)) {
con.Open();
cmd.Parameters.AddWithValue("#Name", ID);
cmd.ExecuteNonQuery();
return "True";
}
}
}
So i want to call this function from javascript function which passes the string value "ID" to the the asp.net function.
this is the javascript function i use
function CallMethod() {
PageMethods.InsertData("hello", CallSuccess, CallError);
}
function CallSuccess(res) {
alert(res);
}
function CallError() {
alert('Errorrr');
}
and i call it from here
<body>
<header>
</header>
<div class="table" id="div1" > </div>
<form id="Form1" runat="server">
<asp:Button id="b1" Text="Submit" runat="server" onclientclick="CallMethod();return false;"/>
<asp:ScriptManager enablepagemethods="true" id="ScriptManager1" runat="server"></asp:ScriptManager>
</form>
</body>
so i have a button and onClick i want to add "Hello" Row to my table but nothing happens and CallError function calls
You can call web method from ajax call in javascript . you need to set url parameter values to function you want to call and you can pass value in the data prameter in json formate.
like this data:"{ParamterName:'VALUE'}
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "YourPage.aspx/YouPageMethod",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Method Called Sucess fully');
},
error: function (result) {
alert("error " + result);
}
});
});
</script>
OR
you can call using PageMethod Eample
<script type="text/javascript">
function callInsert() {
PageMethods.InsertDate(id, OnSucceeded, OnFailed);
}
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
}
/* call this javascript function */
callInsert();
</script>
You will need to include Jquery first in your page. Then you need to add the following Javascript code.
<script type="text/javascript">
var id ="5"; //your id will be stored here
$(document).ready(function () {
$.ajax({
type: "POST",
url: "YourPage.aspx/InsertData" + "&?id=" ,
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Success');
},
error: function (xhr, request, status) {
alert(xhr.responseText);
}
});
});
</script>
You need to have scriptManager in your .aspx page
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
After that you can call the method using
<script type="text/javascript">
function func(){
PageMethods.InsertData(id,success_msg,failure_msg);
}
</script>

How to get javascript values on code behind in c#

I need to get javascript values on code behind in c#.I know i can use hidden field but there is no server control on page for postback.Please tell me how can get vales in code behind.
Here is my code:
<html>
<head>
<title>Facebook Get Logged in User Details UserName,Email,Profile Image</title>
<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
// Init the SDK upon load
window.fbAsyncInit = function () {
FB.init({
appId: 'APPID', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function (response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
var uid = "http://graph.facebook.com/" + response.authResponse.userID + "/picture";
FB.api('/me', function (me) {
document.getElementById('auth-displayname').innerHTML = me.name;
document.getElementById('myJSString').value = me.name;
alert(document.getElementById('myJSString').value);
document.getElementById('Email').innerHTML = me.email;
document.getElementById('profileImg').src = uid;
// document.getElementById('ctl00_CPHDefault_tcTPS_TPProd_ctl01_tcProduction_TPNewT‌​itlesStatus_ChangedRowsIndicesHiddenField').value = uid;
// alert('yyy');
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
$("#auth-logoutlink").click(function () { FB.logout(function () { window.location.reload(); }); });
}
</script>
<h1>
Facebook Login Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
<div id="Result" class="fb-login-button" autologoutlink="true" scope="email,user_checkins">Login</div>
</div>
<div id="auth-loggedin" style="display: none">
Name: <b><span id="auth-displayname"></span></b>(logout)<br />
Email: <b><span id="Email"></span></b><br />
Profile Image: <img id="profileImg" />
<form runat="server">
<asp:HiddenField runat="server" id="myJSString" />
</form>
</div>
</div>
</body>
</html>
You can see there is no server control so how i can get NAME,UID variables in code behind.
Thanks
You can use a hiddenfield server control assign the values you need to it in javascript and assess it on server side. If you do not want post back then you can use jQuery ajax to send values.
Html
<asp:hiddenfield id="ValueHiddenField" runat="server"/>
Javascript
document.getElementById('ValueHiddenField').value = "yourValue";
Code behind
string yourValue = ValueHiddenField.Value;
Using jQuery ajax and web method to send values to code behind, you can find nice tutorial over here.
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: {'yourParam': '123'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Code behind
[WebMethod]
public static void YourMethod(string yourParam)
{
//your code goes here
}
I would investigate the use of ASP.NET AJAX Page Methods, because they allow for script callable stand-alone web services that live in an .aspx page, like this:
Page Method in your code-behind file (call it default.aspx for discussion's sake):
[WebMethod]
public static string SaveData(string name, string uid)
{
// Logic here to do what you want with name and uid values (i.e. save to database, call another service, etc.)
}
jQuery call to default.aspx's SaveData method:
$.ajax({
type: "POST",
url: "default.aspx/SaveData",
data: "{'name':'John', 'uid':'ABC123'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Notes: ASP.NET AJAX Page Methods automatically encode their response to JSON so you will not see any JSON serialization in the code-behind or any serialization logic at all.
For more information about ASP.NET AJAX Page Methods check out Using jQuery to directly call ASP.NET AJAX page methods
You can use following method:
<script language="javascript" type="text/javascript">
function returnString() {
var val = 'sampleValue';
return val;
}
</script>
C# Code to get the return value of the above function:
ClientScript.RegisterClientScriptBlock(this.GetType(), "alertScript", "<script language="javascript">var a=returnString();alert(a);</script>");
Or simply as Adil said, can use hidden field and assign value:
<asp:HiddenField ID="hField" Value="0" runat="server" />
<asp:Button ID="Button1" runat="server" OnClientClick="returnString();"
Text="Button" onclick="Button1_Click" />
script for assigning value:
<script language="javascript" type="text/javascript">
function returnString() {
debugger;
document.getElementById("hField").value = "sampleValue";
}
</script>

Categories

Resources