I am trying to use Datatables within my webforms application.
unfortunatly I get the whole html page instead of json data :'(
this is my code.
<script type="text/javascript">
$(document).ready(function () {
$('#grid').dataTable({
"dataType": 'JSON',
"bServerSide": true,
"sAjaxSource": 'GategoriesManagement.aspx/GetPersonList',
"bProcessing": true,
"aoColumns": [
{ "sName": "d.name" },
]
});
});
</script>
my webmethod
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetPersonList()
{
List<personne> personeList = new List<personne>();
personne person = new personne();
person.name = "test1";
personeList.Add(person);
person = new personne();
person.name = "test2";
person = new personne();
person.name = "test3";
personeList.Add(person);
FormatedList list = new FormatedList();
list.iTotalDisplayRecords = 10;
list.iTotalRecords = 200;
list.aaData = personeList;
var javaScriptSerializer = new JavaScriptSerializer();
string jsonString = javaScriptSerializer.Serialize(list);
return jsonString;
}
and this is the alert that I get in the browser
DataTables warning: table id={id} - Ajax error
it appear that my webmethod is not accessible
what should I do ???
The magic piece of code which makes this work as of 1.10.12 is the ajax parameter. ASP.NET wraps JSON results in the .d property, so you need to execute the callback on that object.
$('#tableId').dataTable(
{
"processing": true,
"serverSide": true,
"stateSave": false,
"lengthMenu": [[10, 30, 100, -1], [10, 30, 100, "All"]], // 1st = page length values, 2nd = displayed options
ajax: function (data, callback, settings) {
$.ajax({
url: "/UserService.asmx/GetUsers",
type: 'POST',
contentType: 'application/json',
dataType: "json",
data: JSON.stringify(data),
success: function (data) {
$spinner.hide();
callback(data.d); // execute the callback function on the wrapped data
}
});
},
I really liked #Echilon answer, but I'd like to add that it's possible to send the Ajax request as GET too.
Having said that, and although OP's example didn't include a parameter in the GetPersonList() method, I'd like to show how parameters would need to be sent on an Ajax request depending if it's a GET or POST** request:
POST request
It doesn't matter if the value is of type int, string, boolean or an object, the way to send data is the same that #Echilon showed. Although here's a little variation:
data: function (data) {
data.parameterName = value;
return JSON.stringify(data);
}
And here's a brief example. Let's suppose that this is your original method:
[WebMethod]
//The parameter could be a int, string or bool
public static string GetPersonList(int|string|bool value)
{
//do something here...
}
And in your Ajax call:
$('#tableId').dataTable(
{
//your DataTable options here
$.ajax({
url: "/UserService.asmx/GetUsers",
type: 'POST',
contentType: 'application/json; charset=utf-8',
//dataType: "json", only include this if you're expecting the result in json format
data: function (data) {
data.value = 10|"Test"|false; //Send the appropriate data according to the parameter type in your method
return JSON.stringify(data);
},
dataSrc: "d.data" //DON'T forget to include this or your table won't load the data
},
// your columns settings here
});
In case you need to send an object here's a brief example. Let's suppose that this is your original method:
class Person
{
public int Id { get; set; }
public string UserName { get; set; }
}
[WebMethod]
public static string GetPersonList(Person person)
{
//do something here...
}
Then in your Ajax call:
var $person = {};
$person.Id = 9;
$person.UserName = "jsmith";
$('#tableId').dataTable(
{
//your DataTable options here
$.ajax({
url: "/UserService.asmx/GetUsers",
type: 'POST',
contentType: 'application/json; charset=utf-8',
//dataType: "json", only include this if you're expecting the result in json format
data: function (data) {
data.person = $person;
return JSON.stringify(data);
},
dataSrc: "d.data" //DON'T forget to include this or your table won't load the data
},
// your columns settings here
});
GET request
If you prefer to use a GET request, then the way to send the data varies a little. If the value is of type int or boolean, you can send it like this:
data: function (data) {
data.parameterName = value;
return data;
}
But if you want to send a string or an object, then you can send it like this:
data: function (data) {
data.parameterName = JSON.stringify(value);
return data;
}
Let's see a brief example. Let's suppose that this is your original method:
[WebMethod]
[ScriptMethod(UseHttpGet = true)] // I didn't include the ResponseFormat parameter because its default value is json
//The parameter could be a int or bool
public static string GetPersonList(int|bool value)
{
//do something here...
}
And in your Ajax call:
$('#tableId').dataTable(
{
//your DataTable options here
$.ajax({
url: "/UserService.asmx/GetUsers",
type: 'GET',
contentType: 'application/json; charset=utf-8',
//dataType: "json", only include this if you're expecting the result in json format
data: function (data) {
data.value = 10|false; //Send the appropriate data according to the parameter type in your method
return data;
},
dataSrc: "d.data" //DON'T forget to include this or your table won't load the data
},
// your columns settings here
});
In case you need to send a string or an object here's a brief example. Let's suppose that this is your original method:
class Person
{
public int Id { get; set; }
public string UserName { get; set; }
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)] // I didn't include the ResponseFormat parameter because its default value is json
//The parameter could be an object or a string
public static string GetPersonList(Person person) // or (string value)
{
//do something here...
}
Then in your Ajax call:
var $person = {};
$person.Id = 9;
$person.UserName = "jsmith";
$('#tableId').dataTable(
{
//your DataTable options here
$.ajax({
url: "/UserService.asmx/GetUsers",
type: 'GET',
contentType: 'application/json; charset=utf-8',
//dataType: "json", only include this if you're expecting the result in json format
data: function (data) {
data.person = JSON.stringify($country);
//data.value = JSON.stringify("Test"); Or this one, depending the parameter of your method
return data;
},
dataSrc: "d.data" //DON'T forget to include this or your table won't load the data
},
// your columns settings here
});
Related
Can't figure out this simple ajax call.
The controller successfully returns the json file as it should, but is logging two zeroes as the values for both the country and amount, which are incorrect. What am I doing wrong here?
controller:
[HttpPost("search")]
public IActionResult test(int country, int amount)
{
System.Console.WriteLine(country);
System.Console.WriteLine(amount);
return Json("success : true");
}
jQuery:
var data = "{ 'country': 2, 'amount': 4}";
$.ajax({
url: "search",
type: "POST",
data: data,
cache: false,
contentType: "application/json",
success: function (data) {
alert("hi"+ data);
}
});
Create a model to hold the desired values
public class TestModel {
public int country { get; set; }
public decimal amount { get; set; }
}
Update the action to expect the data in the body of the request using [FromBody] attribute
[HttpPost("search")]
public IActionResult test([FromBody]TestModel model) {
if(ModelState.IsValid) {
var country = model.country;
var amount = model.amount;
System.Console.WriteLine(country);
System.Console.WriteLine(amount);
return Ok( new { success = true });
}
return BadRequest(ModelState);
}
Client side you need to make sure the data is being sent in the correct format
var data = { country: 2, amount: 4.02 };
$.ajax({
url: "search",
type: "POST",
dataType: 'json',
data: JSON.stringify(data),
cache: false,
contentType: "application/json",
success: function (data) {
alert("hi"+ data);
}
});
Reference Model Binding in ASP.NET Core
You should use JSON.stringify to convert a object into a json string. Do not try to use string concatenation to do this.
Your types for amount do not match what you are sending. A money type should probably be decimal in c#.
Return an anonymous object from the c# method as well and pass that to Json.
The content-type is incorrect, see also What is the correct JSON content type?
[HttpPost("search")]
public IActionResult test(int country, decimal amount)
{
System.Console.WriteLine(country);
System.Console.WriteLine(amount);
// return an anymous object instead of a string
return Json(new {Success = true});
}
jQuery:
var data = JSON.stringify({country: 2, amount: 4.02});
$.ajax({
url: "search",
type: "POST",
dataType: 'json',
data: data,
cache: false,
contentType: "application/json",
success: function (data) {
alert("hi"+ data);
}
});
What am I doing wrong here?
dataType is not required so you can omit that.
4.02 is not an int so you should probably replace that with decimal
and contentType should be application/json
Thanks everyone! Got it working with your help.
It won't work after I remove [FromBody]
[HttpPost("search")]
public IActionResult test([FromBody] string data)
{
System.Console.WriteLine(data);
return Json(new {Success = true});
}
jQuery:
var data = JSON.stringify("{ 'data': 'THOMAS' }");
$.ajax({
url: "search",
type: "POST",
data: data,
cache: false,
contentType: "application/json",
success: function (data) {
alert("hi"+ data);
}
});
I have data like this
[{"billno":"111","amount":"2233.00"},{"billno":"222","amount":"2500.00"},{"billno":"333","amount":"3000.00"}]
I want to store this record in my database, So before that I am trying to send this records to server
Here is my AJAX code:
$('#btnAddVendor').click(function () {
var values = [];
$('table#ContentPlaceHolder1_GridView1 input.checkBoxClass:checked').each(function () {
var $row = $(this).closest('tr').children('td');
values.push({ 'billno': $row.eq(1).text(), 'amount': $row.eq(5).text() });
});
//html_data = JSON.stringify(values);
alert(JSON.stringify(values)); // this alert will display above values
$.ajax({
type: 'POST',
url: 'GPCreateCheque.aspx/setCheqVendorSearchEntry',
data: JSON.stringify(values),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert(result.d);
},
error: function (result) {
alert("Not save");
}
});
})
WebMethod code
public partial class WebForm5 : System.Web.UI.Page
{
[WebMethod]
public static string setCheqVendorSearchEntry(vendorEntry[] values)
{
//here I will write the code to store the records in database
return "Success"; //for testing I return this string
}
}
public class vendorEntry{
public string billno { get; set; }
public string amount { get; set; }
}
I don't know how to receive from ajax. Thanks
Update Error msg
http://localhost:55047/GPCreateCheque.aspx/setCheqVendorSearchEntry 500 (Internal Server Error)
I finally make it run by following:
You need to make it allowed for POST method
[System.Web.Services.WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public static string setCheqVendorSearchEntry(vendorEntry[] values)
{
return "Success"; //for testing I return this string
}
and Default.aspx, your Json Array was not proper. You need to take parameter name (here it is 'values' in setCheqVendorSearchEntry method) in json element and pass it as string or serialize.
var values = '{ "values": [{ "billno": "111", "amount": "2233.00" }, { "billno": "222", "amount": "2500.00" }, { "billno": "333", "amount": "3000.00" }] }';
$.ajax({
type: 'POST',
url: 'Default.aspx/setCheqVendorSearchEntry',
data: values,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert(result.d);
},
error: function (result) {
console.log(result);
}
});
For your learning purpose:
When you console your error in ajax error section, you can find exact error in browser console like this:
Image : https://prnt.sc/gw06sr
I am trying to post some data via jQuery ajax to an Asp.Net MVC controller. I have the follow class which I am working with:
public class InnerStyle
{
[JsonProperty("color")]
public string HeaderColor { get; set; }
[JsonProperty("font-size")]
public string HeaderFontSize { get; set; }
[JsonProperty("font-family")]
public string HeaderFontFamily { get; set; }
}
The post method looks like:
public JsonResult UpdateRecord(InnerStyle innerStyle)
{
//Do some validation
return Json("OK");
}
And my jQuery looks like:
$('#font-size-ddl').change(function () {
var value = $(this).val();
headerObj["font-size"] = value;
console.log(JSON.stringify({ innerStyle: headerObj }));
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Document")",
data: JSON.stringify({ innerStyle: headerObj}),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
});
The console.log in the above change event produces the following JSON string:
{"innerStyle":{"text-align":"","font-size":"20px","color":""}}
Now the issue I am having is if I set a break point on my UpdateRecord Action and see what is coming through the innerStyle object is null. Can someone tell me where I am going wrong please.
I tried using the below code and it's working fine.
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Document")",
data: JSON.stringify({"text-align":"","font-size":"20px","color":""}),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
I simply removed the parameter name "innerStyle". I just noticed one thing which might be a typo error. You are passing a property "text-align":"" instead of "font-family". So it's not populating all properties inside the controller's action UpdateRecord(InnerStyle innerStyle). You should pass similar to the below json object to map the entire object on controller's action UpdateRecord(InnerStyle innerStyle)
{
"color": "sample string 1",
"font-size": "sample string 2",
"font-family": "sample string 3"
}
#Code, your code is fine. It's just you cannot use [Json Property] while you are hitting controller via ajax. you have to use real class properties.
$('#font-size-ddl').change(function () {
var value = $(this).val();
var headerObj = {};
headerObj["HeaderColor"] = "Red";
headerObj["HeaderFontSize"] = value;
headerObj["HeaderFontFamily"] = "Arial";
console.log(JSON.stringify({ custom: headerObj }));
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Employee")",
traditional: true,
data: JSON.stringify({ custom: headerObj }),
dataType: JSON,
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
});
I want to send some data back form my JavaScript to WCF. This object I send back needs to get loaded in the Foo class. If I debug the code I can see the function (Sting) gets called. But if i check whats in the the object I got returned, this object is null.
This indicates the data can't be stored in in the Object of WCF. The WCF works find when I send data to the JavaScript with Ajax. FYI I use .NET 3.5
this is how I try to receive the data: WCF:
namespace TPlatform
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DataService
{
[OperationContract]
public void Sting(Foo postData)
{
var x = 1; //Breakpoint, postData is null?
}
}
[DataContract]
public class Foo
{
[DataMember]
public string Bar;
}
}
JavaScript:
var fooObject = { "Bar": "test" };
function sendDataToWcf(object) {
$.ajax({
type: "POST",
url: "DataService.svc/Sting",
data: JSON.stringify(fooObject),
processData: false,
contentType: "application/json",
dataType: "json",
success: suckcess,
error: showError
});
}
What am I doing wrong? How can I read the the data into my class?
Try this
$.ajax({
type: 'POST',
url: url,
//dataType: 'json',
contentType: "application/json",
data: JSON.stringify({ postData: fooObject}),
success: function (response) {
successCallback(response);
},
error: function (xhr, status, error) {
handleError(xhr, status, error);
}
});
Update: Change:
var fooObject = { "Bar": "test" };
too
var fooObject = { Bar: "test" };
and dont send the datatype.
$(document).ready(function () {
$.ajax({
url: 'LeadPipes/LeadCounts',
type: 'POST',
contentType: 'application/json',
async: false,
success: function (data) {
alert(data)
}
});
});
I am using the ajax call above to get a model back how would i use the model object in the success function. As in I need to be able to use the data like a views model like #model.Type lets say. how could i do that with the json data in the success?
The data object contains the properties passed down via the server.
You can then access them like:
var name = data.Name;
var testData = data.TestData;
Your Action could look like:
public JsonResult LeadCounts()
{
return Json(new { name = "Darren", testData = "Testing" });
}
In MVC3 you could do it like this:
public ActionResult LeadCounts()
{
var data = new { Count = 1, Something = "Something" };
return Json(data, JsonRequestBehavior.AllowGet);
}
In view:
$(document).ready(function () {
$.ajax({
url: 'LeadPipes/LeadCounts',
type: 'POST',
contentType: 'application/json',
async: false,
success: function (data) {
alert(data.Count);
}
});
});