Calling simple AJAX WebMethod always results in "fail" callback - c#

Below code is my server side code. (C#)
[WebMethod]
public static string InsertCV(string edu)
{
return "";
}
And Below code is my client side code. (ASP.NET)
var edu = {"education":[{"university":"111","speciality":"222","faculty":"333","degree":"444","start":"555","end":"666"}]}
var post = $.ajax(
{
type: "POST",
data: edu,
url: "Add_CV.aspx/InsertCV",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false
})
post.done(function (data, teStatus, jqXHR) {
if (data.d == "")
{ alert("ok"); }
});
post.fail(function (jqXHR, e) {
alert("error");
});
I would like to send user's data to server with ajax post method. But everytime post.fail() function executes.
Please help me that where is my mistake.
May be in server side InsertCV(string edu) , string is not appropriate for this situtate. I don't know.

This:
public static string InsertCV(string edu)
is expecting a single parameter called edu that is of type string. Your AJAX call is instead passing in an un-named JavaScript object, which is not a string. The framework code that is trying to parse the request is never matching your InsertCV method at all, and eventually gives up with a 500 - Internal Server Error result.
To pass a complex structure like this into a WebMethod you need to define a compatible .NET class to deserialize into. For instance:
// outer type for the parameter
public class EduType
{
public Education[] education;
// inner type for the 'education' array
public class Education
{
public string university;
public string speciality;
public string faculty;
public string degree;
public string start;
public string end;
}
}
[WebMethod]
public static string InsertCV(EduType edu)
{
return edu == null ? "null" : string.Format("{0} Items", edu.education.Length);
}
If the JSON string will deserialize into this format then this method is the one that should get called.

I found the solution for your problem.
Here is the code :
as cs page :
[WebMethod]
public static string InsertCV(object education)
{
return "";
}
and for calling this method :
var edu = { "education": [{ "university": "111", "speciality": "222", "faculty": "333", "degree": "444", "start": "555", "end": "666"}] }
var post = $.ajax(
{
type: "POST",
data: JSON.stringify(edu),
url: "ServiceTest.aspx/InsertCV",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false
})
post.done(function (data, teStatus, jqXHR) {
if (data.d == "")
{
alert("ok");
}
});
post.fail(function (jqXHR, e) {
alert("error");
});
if this is helpful to you, Please mark as correct.
Thanks.

As asked by #user2864740, your method InsertCV does not do anything. I suggest starting by testing your webmethod by setting a breakpoint in the InsertCV method, to see if this get hit when browsed to. Secondly from your AJAX post method you send a JSON array, but in the InsertCV method, you only expect a single string. This have to match. When you can trigger the WebMethod from your AJAX call, then go on and add handling for writing to a backend database

Related

.net core 3.1 post ajax list of objects to MVC controller no data arriving

I'm trying to post a list of objects to a MVC controller via AJAX, but when it gets to the controller the editedPrices parameter is 0.
What am I doing wrong? Currently I'm not sure if the issue is with the data I'm sending or the controller.
Java Script:
$(document).ready(function () {
var newPrices = [
{ "id": "1", "wePrice" : "99", "wdPrice":"79" },
{ "id": "2", "wePrice" :"89", "wdPrice":"59" }
];
editedPrices = JSON.stringify(newPrices);
$.ajax({
contentType: 'application/json; charset=utf-8',
type: "POST",
url: "#Url.Action("EditRates")",
data: {editedPrices : newPrices},
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function (req, status, error) {
alert(error);
}
});
});
c# object
public class EditPrices
{
public string id { get; set; }
public string wePrice { get; set; }
public string wdPrice { get; set; }
}
controller
[HttpPost]
public int EditRates(List<EditPrices> editedPrices )
{
return editedPrices.Count();
}
I've tried using the [FromBody] attribute, but then the editedPrices parameter is null (as opposed to showing a count of 0).
Edit
Just to clarify, I can see that some data is being sent in the AJAX request. And I can see that the controller is being called. So the AJAX request it self is working. But I'm either sending the data in the 'wrong' format, or there's something wrong with how I'm trying to receive it.
You should just change this line:
...
data: JSON.stringify(newPrices),
...
You are making another object with {editedPrices : newPrices}. Your API accepting array.

Is there any equivalent code for asp.net web-form of MVC JsonResult and Json? [duplicate]

The objective is to call a method which does it's thing then returns a JSON object.
I'm new to JSON.
I have a default.aspx and in it the following code. Now I want an ordinary method in Default.aspx.cs to run on the click event here.
$(".day").click(function (event) {
var day = $(event.currentTarget).attr('id');
if (day != "") {
$.ajax(
{
type: "POST",
async: true,
url: 'Default.aspx?day=' + day,
data: day,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("SUCCESS:" + msg);
// $(".stripp img").attr('src', "data:image/jpg;" + msg);
// $(".stripp").show();
},
error: function (msg) {
console.log("error:" + msg);
}
});
}
});
Default.aspx.cs looks similar to this:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["day"] != null)
GetFile(Request.QueryString["day"]);
}
public string GetFile(string day)
{
string json = "";
byte[] bytes = getByteArray();
json = JsonConvert.SerializeObject(bytes);
return json;
}
Where am I going wrong here?
Should I be using this in some way or is it only applicable in Web Services?
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
I would suggest an HttpHandler. No page lifecycle (so it is blazing fast) and much cleaner code-separation, as well as reusability.
Add a new item to your project of type "Generic Handler". This will create a new .ashx file. The main method of any class that implements IHttpHandler is ProcessRequest. So to use the code from your original question:
public void ProcessRequest (HttpContext context) {
if(String.IsNullOrEmpty(context.Request["day"]))
{
context.Response.End();
}
string json = "";
byte[] bytes = getByteArray();
json = JsonConvert.SerializeObject(bytes);
context.Response.ContentType = "text/json";
context.Response.Write(json);
}
Change the url in your AJAX call and that should do it. The JavaScript would look like this , where GetFileHandler.ashx is the name of the IHttpHandler you just created:
$.ajax(
{
type: "POST",
async: true,
url: 'Handlers/GetFileHandler.ashx',
data: "Day=" + $.toJSON(day),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("SUCCESS:" + msg);
},
error: function (msg) {
console.log("error:" + msg);
}
});
Another small point to consider, if you need access to the Session object from within the Handler code itself, make sure to inherit from the IRequiresSessionState interface:
public class GetFileHandler : IHttpHandler, IRequiresSessionState
Yes your method has to be static with the WebMethod attribute
Basic example:
CS
using System;
using System.Web.Services;
public partial class _Default : System.Web.UI.Page
{
[WebMethod(EnableSession=false)]
public static string HelloWorld()
{
return "Hello World";
}
}
Javascript
<script>
$.ajax({
type: "POST",
url: "Default.aspx/HelloWorld",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function(msg) {
console.log(msg.d);
}
});
</script>
Been a while since I worked with webforms, but if remember correctly it should work if you put the webmethod attribute over GetFile method and make that method static.
[WebMethod]
public static string GetFile(string day)
Furthermore, how you post data in ajax method is a bit off. Remove querystring day from url and data should be in json format, something like {"day":day}

Receive json object through ajax post request

UNABLE TO DETECT PROBLEM
I am trying to get data from server using ajax post request but when ajax request hits back end c# method its data part gets null
here is my js code
let da = '{"sidx":'+sid+',"idx":'+cur+'}';
da = JSON.parse(da);
$.ajax({
type: "POST",
url: "../RegSaleman/next",
data: {x:da},
datatype: "Json",
complete: function (dataret) {
}
});
and c# code is
[HttpPost]
public JsonResult next(JsonResult x)
{
}
You're trying to read JsonResult, which is wrong. This class used for response from server.
You can create some data model (simple class) that will be mapped automatically by MVC framework.
Let's assume that you have JSON object:
{
"id": "someValue",
"foo" : 3,
"bar" : "bar string"
}
and you can create a class
public class MyClass
{
public string Id {get;set;}
public int Foo {get;set;}
public string Bar {get;set;}
}
As you can see, it even can map variables in different case (like Foo and "foo"), but this behavior could be altered in case of need.
And your method will be:
[HttpPost]
public JsonResult next(MyClass x)
{
}
var obj = new Object();
$.ajax({
type: "POST",
url: "/RegSaleman/next",
data: JSON.stringify(o),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
},
error: function (response) {
}
});

How exactly does a JSON.stringify automatically map to my DTO

I have an object in jquery:
function SaveRequest() {
var request = BuildSaveRequest();
$.ajax({
type: "POST",
processData: false,
data: JSON.stringify({'model':request}),
url: "somepage.aspx/JsonSave",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response, status, xhr) {
},
error: function (res, status, exception) {
}
});
return false;
}
function BuildSaveRequest() {
var request = {
customerName: $("#CustomerName").val(),
contactName: $("#ContactName").val(),
};
return request;
}
And I have the following c# code:
[WebMethod]
public static string JsonSave(MyModel model)
{
}
}
public class MyModel
{
public string CustomerName { get; set; }
public string ContactName { get; set; }
}
When the ajax call goes, the web method JsonSave automatically place the values (CustomerName, & ContactName) from the jquery object 'request' into the appropriate properties in object 'model'. How does it know to do that???
Added answer from comments:
Model Binders are a beautiful thing.
I would recommend reading the source found here this is for MVC but I'm pretty sure it acts the same in webforms as well.
It is really smart and checks the in request for the data so it doesn't really matter if you use webforms or mvc. You can even create our own.

Having some trouble making a simple ajax call

I started switching things over to [WebMethod]s but started having trouble and decided I needed to do some more research on how to use them properly.
I put the following in $(document).ready()
$.ajax({
type: "POST",
data: "{}",
url: "http://localhost:3859/Default.aspx/ajxTest",
dataType: "json",
success: function (msg, status) {
alert(msg.name + " " + msg.value);
},
error: function (xhr, status, error) {
var somethingDarkside; //only to put a breakpoint in.
alert(xhr.statusText);
}
});
My [WebMethod]
[WebMethod]
public static string ajxTest()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
DummyString dum = new DummyString("Please","Work");
string jsonString = ser.Serialize(dum);
return jsonString;
}
I never get "Please work". I get "undefined undefined" I'm able to debug in VS and the call enters the [WebMethod], the return string looks correct for JSON but I haven't been able to get a successful call out of it yet. I've got parse errors, transport errors. Everything is inconsistent but nothing has ever been right. I've had up to 47 different blogs, SO posts and google group tabs up today, I can't quite crack it.
The xhr.statusText status is OK as posted. I am getting a status parse error. I'm lost.
Thanks in advance.
EDIT: jQuery 1.9.1
EDIT2: DummyString object
public class DummyString
{
public string name { get; set; }
public string value { get; set; }
public DummyString(string n, string v)
{
name = n;
value = v;
}
}
EDIT 3: Also I have <asp:ScriptManager EnablePageMethods="true" ...
Simplify to:
$.ajax({
type: "POST",
url: "Default.aspx/ajxTest",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('success');
},
error: function (data) {
alert('fail');
}
});
and
[WebMethod]
public static string ajxTest()
{
return #"{ ""hello"":""hola"" }";
}
and test. (the above will work)
Service return response in .d parameters try following
msg.d.name

Categories

Resources