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
Related
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) {
}
});
I have a test js function that should post data to webapi by Post method
function test() {
var puffs = [];
var puffObject = {
id: "2735943",
priority: "1"
};
puffs.push(puffObject);
puffs.push(puffObject);
var dto =
{
po: puffs
};
$.ajax({
type: "POST",
url: "../api/PuffPriority/",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(dto),
dataType: "json",
success: function (data, status) {
if (data) {
console.log("Welcome");
} else {
console.log("No data");
}
},
error: function (error) {
console.log("Error");
}
});
}
In the controller class i have
public void Post(PuffPriority[] po){
//Do something here with po, but po is always empty
}
where PuffPriority Model is
public class PuffPriority
{
public string id { get; set; }
public string priority { get; set; }
}
I dont know whats wrong , the values are sent by JS but api Controller don't fetch it :( Please help, i have already wasted a lot of time.
You have a bug in your code.
Simply change
url: "../api/PuffPriority/"
to
url: "../api/Post/"
or change your method name from Post to PuffPriority
Changed
public void Post(PuffPriority[] po){
//Do something here with po, but po is always empty
}
To
[FromBody]List<PuffPriority> po{
//Do something here with po, but po is always empty
}
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.
I am using jquery 1.8 to post data to ASP.Net 4 MVC 2 like this
PostData('Home/Login',{ "username": $("#username").val(),"password": $("#password").val()})
function PostData(url, data) {
$.ajax({
url: url,
data:data,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
Success:successFunction, Error: ErrorFunction
});
};
My model
namespace FmsMvc.Models
{
public class UsersModel
{
public int UserID { get; set; }
public string Role { get; set; }
public string Email { get; set; }
public DateTime ts { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
}
My Controller
[HttpPost]
public JsonResult Login(UsersModel u)
{
if (doSomething(Prop1, Prop2)
return Json(null); // Success
return Json(new { Status:'success',Msg:" Your username"+u.username });
}
My controller does not get the data. It gets null when debugging.
what am i doing wrong?
NOTE
I deleted all the javascript in the Scripts folder, as I am using a custom script
Have you tried JSON.strinfigy-ing your data before POSTing?
function PostData(url, data) {
$.ajax({
url: url,
data:JSON.stringify(data),
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
Success:successFunction, Error: ErrorFunction
});
};
Try it like this:
var data = { "username": $("#username").val(),
"password": $("#password").val()
};
PostData('Home/Login',JSON.stringify(data));
You can use the JQuery .post() method which will parse the values for you
var url = '#Url.Action("Login", "Home")'; // beter to use this rather than hardcoding
var userName = `$("#username").val();
var password = $("#password").val();
$.post(url, { Username: userName, Password: password }, function(result) {
// do something with the result you returned from the action method
alert(result.Msg);
});
Note, only properties Username and Password will be set in the model. The other properties will be their default values.
After much debugging, i found the culprit
in my ajax function above i have this two line
contentType: 'application/json; charset=utf-8',
dataType:'json',
Somehow, this should not be. when i submitted the form with the two lines present, this is what i saw in chrome dev
But when i removed the line contentType: 'application/json; charset=utf-8', so that the $.ajax is now
$.ajax({ // create an AJAX call...
type: 'post', // GET or POST
url: url, // the file to call
dataType:'json',
data: data, // get the form data
Success:successFunction, Error: ErrorFunction
});
when i look in chrome dev after submit, i see this, which was not there before
I dont' know why this is the case, i will try in other browsers to see if it all works
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