Webforms ASP.NET Ajax JSON Not Valid
Webforms ASP.NET Ajax JSON Not Valid
Hello,
I'm trying to start with a simple Webforms ASP.NET 4.6.5 application using DataTables. I've downloaded the sample project and imported the sample database. Now I'm trying to send the data from the ASPX server-side to the client-side. The request is returning a JSON not valid. I'm a little unfamiliar with some of the concepts, I cannot understand what is wrong with the JSON generated sent and received. It seems like the same data sent is being received. I've attached the response received on the client side and well the JSON data being sent. On the console, it shows JSON is not valid(image attached)
The server-side code is here(I've pieced it together from the sample project and other examples from this forum) :
[WebMethod]
public static string Get_data()
{
var request = HttpContext.Current.Request;
var settings = Properties.Settings.Default;
using (var db = new Database(settings.DbType, settings.DbConnection))
{
var response = new Editor(db, "datatables_demo")
.Model<StaffModel>()
.Field(new Field("first_name")
.Validator(Validation.NotEmpty())
)
.Field(new Field("last_name"))
.Field(new Field("age")
.Validator(Validation.Numeric())
.SetFormatter(Format.IfEmpty(null))
)
.Field(new Field("extn")
.Validator(Validation.Numeric())
)
.Field(new Field("start_date")
.Validator(Validation.DateFormat(
Format.DATE_ISO_8601,
new ValidationOpts { Message = "Please enter a date in the format yyyy-mm-dd" }
))
.GetFormatter(Format.DateSqlToFormat(Format.DATE_ISO_8601))
.SetFormatter(Format.DateFormatToSql(Format.DATE_ISO_8601))
)
.Field(new Field("salary")
.Validator(Validation.Numeric())
.SetFormatter(Format.IfEmpty(null))
)
.Process(request)
.Data();
// HttpContext.Current.Response.ContentType = "text/json";
// HttpContext.Current.Response.Write(JsonConvert.SerializeObject(response));
// HttpContext.Current.Response.End();
var serializer = new JavaScriptSerializer();
string jsonResult = serializer.Serialize(response);
return jsonResult;
}
The client side is here:
<script type="text/javascript">
var editor; // use a global for the submit and return data rendering in the examples
$(document).ready(function () {
editor = new $.fn.dataTable.Editor({
"ajax": {
type: 'POST',
url: 'Ajax.aspx/Get_data',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
dataSrc: function (response) {
var tr = JSON.parse(response.d);
console.log(tr);
return tr;
}
},
"table": "#example",
"fields": [{
"label": 'First name:',
"name": 'first_name'
},
{
"label": 'Last name:',
"name": 'last_name'
},
{
"label": 'Age:',
"name": 'age'
},
{
"label": 'Extension:',
"name": 'extn'
},
{
"label": 'Start date:',
"name": 'start_date',
"type": 'datetime'
},
{
"label": 'Salary:',
"name": 'salary'
}
],
});
new DataTable('#example', {
"ajax": {
type: 'POST',
url: 'Ajax.aspx/Get_data',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
dataSrc: function (response) {
var tr = JSON.parse(response.d);
console.log(tr);
return tr;
}
},
"columns": [
{
"data": null,
"render": (data) => data.first_name + ' ' + data.last_name
},
{ "data": 'age' },
{ "data": 'extn' },
{ "data": 'start_date' },
{ "data": 'salary', render: DataTable.render.number(null, null, 0, '$') }
],
"layout": {
"topStart": {
"buttons": [
{ "extend": 'create', editor: editor },
{ "extend": 'edit', editor: editor },
{ "extend": 'remove', editor: editor }
]
}
},
select: true
});
});
</script>
I appreciate the help. Let me know if further information is needed.
Answers
https://justpaste.it/izhvo
JSON datafrom Visual Studio inspector.
I have a feeling that
tr
is still a string. Change the console output to usetypeof
to see whattr
is, like this:What is the result? My guess is its a string not an object.
I'm not familiar with ASP.NET but my guess is this:
is converting the Datatables response data to a JSON string then ASP.NET is again serializing the full response resulting in
jsonResult
being serialized twice.If this is the case then you will need to either just return the raw data from the
Get_data()
function so its serialized once or add an additionalJSON.parse()
toajax.dataSrc
to converttr
to an object. For example:Kevin
Thanks Kevin. The data is still not displayed with with the added
JSON.parse()
. In the variable inspection theresponse.data
holds the information:The console returns:
Also with the raw data only from the server side the result is the same:
It looks like you might not need to use
JSON.parse()
as it looks like the reposnse data has already been parsed to a Javascript object. Possibly just pointing to theresponse.d.data
usingajax.dataSrc
is all you need. For example:Kevin
I ,made some edits to my previous response. See above.
Kevin
Thanks Kevin! That almost did the trick. I can now have the data displayed with this:
But one last thing. The New, Edit and Delete functions do not function properly. When I click any of these buttons, the modal pop-up appears, but when I click on Create, Update or Delete(on each modal pop-up) nothing happens, the pop-up does not close and the data does not get updated. What could I be missing? Here is the client side Editor related code:
The Editor's
ajax
option does not have adataSrc
option. It expects the data to be returned in the format discussed in the Client / server docs. I believe the only option to do something similar is to use the ajax option as a function. See the last example in the docs. Probably you will need something like this:Call the
success
callback like thissuccess(json.data);
.Kevin
Thanks again. I can get the data displayed with the following(again piecing from other posts from this forum):
When I click the create button the modal pop-up appears but after inserting the information and clicking creating nothing happens. When clicking on Edit or Delete, I get the following error( the idSrc has been added to the ajax parameters):
I apologize, I acknowledge I might be missing basic code here, I just can't seem to find the right information. I apreciate all the help.
Have you read the technote at the link in the error?
https://datatables.net/manual/tech-notes/14
You have
"idSrc": "id",
. Does your row data have anid
object?Looking back at your sample JSON output you don't have an
id
but do have the defaultDT_RowId
. Note this comment in the technote:If you are using
DT_RowId
for your unique identifier then you don't need to defineidSrc
asDT_RowId
is the default value.Kevin
Use the browser's network inspector tool to monitor the XHR requests and responses. This will allow you to validate that the responses meet the Editor client/server data requirements. If the response is in the
response.d
object then you will need to use the Editor'sajax
as a function to extract the required data structure.Kevin
Thanks. Removing the idSRC fixed the issue. However, the New, Edit, and Delete still don't update the DB.
Here is the Network inspector when I click Update:
On the server side the Params field from Http.Request is empty:
When I test the sample project the Param field is populated:
Here the Network Inspector:
Any idea where I could start troubleshooting this?
Try removing:
If you are using the Editor server-side libraries, they will parse the POSTed data, so no need to send it as a JSON string in the request body. Regular HTTP parameters will do fine.
Allan
Unfortunately that did not work. But thank you for the help!
Are you able to PM me a link to the page in question?
If you look at the "Payload" section of the Ajax request when you make a create or edit action, does it now show all of the parameters being submitted?
Allan
Sorry for the delay. I'm running a local project,, still in development with Visual Studio, so I'm not sure how I could expose for external access. As for the Payload here is what I get when I edit a row:
I have this:
If I remove it as you suggested I get an error 500.
Could you also try removing
contentType: 'application/json; charset=utf-8',
please? I think that is telling .NET to expect JSON in the request body. We just want HTTP parameters like in the demo package.Allan
I removed it then I get this error:
Did you follow the troubleshooting steps at the link in the error?
https://datatables.net/manual/tech-notes/1
Let us know what you find.
Kevin
Hi Kevin, I did. The result of the debugging are the screenshots of my reply on Feb-2nd, where is the Params field from Http.Request is empty, and my reply on Feb-05 with a screenshot of the Network monitor of the Payload. Thanks for all the help.
The Payload tab shows the data sent to the server. Look at the Preview or Response tabs to see the response.
Its better to post the current screenshots than to refer to old screenshots that weren't generated from the current error. Its better for us to troubleshoot rather than assume something and troubleshoot the wrong thing.
Kevin
Hi Kevin, I ende up up adopting a different approach, utilizing the controller method. Thanks for all the help.