Call function from class in c# using jquery ajax - c#

I have been able to call the function using ajax using following code
function AjaxCall() {
$.ajax(
{
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/Server_HelloWorld',
datatype: 'json',
success: function (result) { alert(result.d); }
})
}
using System.Web.Services;
using System.Web.Script.Services;
aspx.cs Ajax Webmethod,
[WebMethod]
public String Server_HelloWorld()
{
return "Hello, How are you?";
}
But if i don't have any .aspx page, i have only .html page with a class say myfunclass.cs. How do i call the same function from here. I have tried but fail
$.ajax(
{
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'myfunclass.cs/Server_HelloWorld',
datatype: 'json',
success: function (result) { alert(result.d); }
})

You cant just call *.cs file. You need to create some backend, like ASP.NET MVC Web API like in example here

Related

send List into mvc controller with ajax

I have a List which look like the following
I want to send this list into my controller,
I am using ajax call to send data from client side to server side
here is my ajax call
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
and my method in controller
public bool updateHoliday(List<Holidaysclass> data)
{
for (var i = 0; i < data.Count(); i++)
{
insertHolidays(data.ElementAt(i).Date, data.ElementAt(i).Day, data.ElementAt(i).HolidayName, data.ElementAt(i).isActive, data.ElementAt(i).currentYear, data.ElementAt(i).isHolidayWeekend, data.ElementAt(i).OfficialID);
}
return true;
}
here my List<Holidaysclass> data is showing null
what can I do here?
To send data from browser to controller you need to use POST type and then pass data inside ajax call. you can directly map your entites in action method.
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
and in controller put HttpPost Data Annotation
[HttpPost]
public bool updateHoliday(List<Holidaysclass> data)
{
for (var i = 0; i < data.Count(); i++)
{
insertHolidays(data.ElementAt(i).Date, data.ElementAt(i).Day, data.ElementAt(i).HolidayName, data.ElementAt(i).isActive, data.ElementAt(i).currentYear, data.ElementAt(i).isHolidayWeekend, data.ElementAt(i).OfficialID);
}
return true;
}
Using ajax get method we cant send data from client to server is not best way. try using POST method send data from client to server.
Reference : https://api.jquery.com/jquery.post/
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
......
});
You can do it like this :
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/PassThings',
data: things,
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
Please follow this link for more information :
link
You can not post data in get request. Instead you need to use POST type request.
Here is your updated request.
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
Also your action should have [HttpPost] annotation.
try this:
$.ajax({
url: '/Main/updateHoliday',
data: {list: d.weekendLeave},
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
[HttpPost]
public bool updateHoliday(List<Holidaysclass> list)

Can't get ajax call with parameters to hit my C# function

Ajax:
var test = "test";
$.ajax(
{
type: "POST",
url: "project/function",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { input: test },
success: function (response) {
$("#lblMsg").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
C# function:
[WebMethod]
public void function(string input)
{
}
The connection is made successfully when I don't include a parameter. I have tried different single and double quote permutations of the 'data' portion of the ajax call, to no avail.
I have also tried setting the dataType to "text" with similar results.
What am I missing?
I would suggest that you shouldn't send your data as JSON. Just remove the
contentType: "application/json; charset=utf-8"
and jQuery will serialise the data into normal url-encoded form data format, which is what the WebMethod is expecting.
try this one may be resolve your issue
var test = "test";
$(document).ready(function () {
$.ajax({
type: "POST",
url: "project/function",
contentType: "application/json; charset=utf-8",
datatype: "json",
data:JSON.stringify({ 'input': test }),
success: function (response) {
$("#lblMsg").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
});

jquery $.when not working by waiting function in master page

i have some problem when i use jquery.when function in web form using master page
This is my code in web form using master page
$(document).ready(function(){
$.when(masterPageFunction()).done(function(){
webFormFunction();
});
})
And this my master page
function masterPageFunction() {
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
}
})
}
})
}
result is web function is running when master page function not done
please help, thank you so much
You're close, but the when, then and done functions rely on promises. You aren't returning any promises in your code, so it's just running straight through.
First, you'll need to obtain the result of the promise after it completes in the done function in your master page. We'll do that by adding a response parameter to the callback, then passing it through to webFormFunction.
$(document).ready(function(){
$.when(masterPageFunction()).done(function(response){
webFormFunction(response);
});
})
Next, we need to add a promise to masterPageFunction and return it. You resolve the promise with the response you want to send back to the done function in your master page. Like so:
function masterPageFunction() {
// Create the promise
var deferred = $.Deferred();
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Resolve the promise with the response from $.ajax
deferred.resolve(response);
}
});
}
});
// Return the promise (It hasn't been resolved yet!)
return deferred.promise();
}
In this way, webFormFunction won't be called until the second ajax call completes, which resolves the promise.

Send just a string from $.ajax to c#

This is supposedly very easy but for some reason it has taken me about 2 hours and countless searches and nothing is working
I am trying to call a WebMethod from ajax, and it works quite well.
As soon as I try to change the c# function to accept parameters and send one from ajax everything fails
Code:
c#:
[WebMethod]
public static string GetBGsForSelectedCrop(string cropName)
{
return "asdasd";
}
jquery:
$().ready(function () {
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetBGsForSelectedCrop",
data: "Wheat",
success: function (msg) {
$("#Result").text(msg.d);
alert(msg.d);
console.log(msg)
}
});
});
});
I have tried datatype: "json", contentType: "application/json; charset=utf-8", and tried without both and datatype: "string" and datatype: "text", GET, data: "{'ABCD'}, data:{"cropName: Wheat"}, and data: json.Stringify("Wheat").
I get undefined for msg.d and sometimes HTTP error 500 if I take it too far.
What am I missing? It is just a simple task and should've been done in seconds..
As the guys in the comments says, you need to change your code for:
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetBGsForSelectedCrop",
data: JSON.stringify({ cropName: "Wheat" }),
dataType:'text',
contentType: "application/json; charset=utf-8",
success: function (msg) {
$("#Result").text(msg.d);
alert(msg.d);
console.log(msg)
}
});
});
Your error is the data is no good encoded, and you are missing the datatype.
What is the stringfy It Convert any value to JSON.

Unknown web method parameter method name

I'm building a Web Application in which I'm trying to call a WebMethod in a WebForm, I've tried every single page in google but I'm still getting nothing. This is an example of the Jquery Ajax Call
$.ajax({
type: "Post",
url: "Default.aspx/Return",
data: {dato:'Hello'},
contentType: "application/json; chartset:utf-8",
dataType: "json",
success:
function (result) {
if (result.d) {
alert(result.d);
}
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});
And this is the WebMethod in the codebehind
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public static string Return(string dato)
{
return dato;
}
You can't access a Static method this way. Remove the "Static" reference and it will work. Also, like someone else said - do not use that as your method name "Return".
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string Return(string dato)
{
return dato;
}
I think, on your success event the function with result is used, which is a string and u are trying to access property named d assuming result is an object.
use of only alert(result);
User F12 tool to debug and find your error.
Make sure that you have enabled page methods in your ScriptManager element:
<asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true" />
and your method
$.ajax({
type: "Post",
url: '<%= ResolveUrl("~/Default.aspx/Return") %>',
data: {dato:'Hello'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (result) {
alert(result);
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});
Try this
var url = window.location.pathname + "/Return";
$.ajax({
type: "Post",
url: url,
data: {dato:'Hello'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (result) {
alert(result.d);
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});`

Categories

Resources