I am receiving null in both ProductData and ProductDetailsData when data is sent from ajax to controller. What could be the issue ?
IN CONTROLLER :
public bool UpdateProduct(Entity_Product ProductData, Entity_ProductDetails ProductDetailsData)
{
return Json(DrugService.UpdateProduct(ProductData, ProductDetailsData));
}
IN JS FILE :
$(document).on("click", "#btn_update", function () {
//Prepare data
var ProductDataArray = [];
var ProductDetailsDataArray = [];
ProductDataArray.push({
"Name": $('#txt_drugname').val(),
"CommercialName": $('#txt_drugcommercialname').val(),
"PackageType": $("#dd_packagetype option:selected").val(),
"DrugType": $("#dd_drugtype option:selected").val(),
"DrugCode": $('#txt_drugcode').val(),
"ProductId": $('#hdn_productid').val(),
"Administration": $('#txt_administration').val(),
"Manufacturer": $('#txt_manufacturer').val(),
"Price": $('#txt_price').val(),
"Strength": $('#txt_stregnth').val(),
"StregnthUnit": $("#dd_stregnthunit option:selected").val(),
"Barcode": $('#txt_barcode').val(),
"IsEnabled": $("#dd_isenabled option:selected").val(),
"UpdatedOn": new Date(),
"UpdatedBy": 'UserNme',
});
ProductDetailsDataArray.push({
"ProductId": $('#hdn_productid').val(),
"ProductDetailsId": $('#hdn_productdetailid').val(),
"Length": $('#txt_Legnth').val(),
"Width": $('#txt_width').val(),
"Height": $('#txt_height').val(),
"ConversionRate": $('#txt_conversion').val(),
"DrugForm": $("#dd_drugform option:selected").val(),
"StoredAs": $("#dd_storedas option:selected").val()
});
//Send data
$.ajax({
url: '/Drug/UpdateProduct/',
type: 'POST',
data: { 'ProductData': ProductDataArray, 'ProductDetailsData': ProductDetailsDataArray },
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
}
});
});
You have several issues in both AJAX and controller action method:
1) You're tried to pass arrays into data using contentType set to application/json without doing JSON.stringify() first, therefore it won't work since array required to pass either as JSON string or use traditional: true setting.
2) The action method parameter types are not set to array but a single entity class like viewmodel, you need to declare an object instead of array.
3) The controller action uses bool return type which should use JsonResult (or ActionResult) type.
Based from those mistakes mentioned above, try to use setup like below:
jQuery
$(document).on("click", "#btn_update", function () {
var ProductDataArray = {
"Name": $('#txt_drugname').val(),
"CommercialName": $('#txt_drugcommercialname').val(),
"PackageType": $("#dd_packagetype option:selected").val(),
"DrugType": $("#dd_drugtype option:selected").val(),
"DrugCode": $('#txt_drugcode').val(),
"ProductId": $('#hdn_productid').val(),
"Administration": $('#txt_administration').val(),
"Manufacturer": $('#txt_manufacturer').val(),
"Price": $('#txt_price').val(),
"Strength": $('#txt_stregnth').val(),
"StregnthUnit": $("#dd_stregnthunit option:selected").val(),
"Barcode": $('#txt_barcode').val(),
"IsEnabled": $("#dd_isenabled option:selected").val(),
"UpdatedOn": new Date(),
"UpdatedBy": 'UserNme',
};
var ProductDetailsDataArray = {
"ProductId": $('#hdn_productid').val(),
"ProductDetailsId": $('#hdn_productdetailid').val(),
"Length": $('#txt_Legnth').val(),
"Width": $('#txt_width').val(),
"Height": $('#txt_height').val(),
"ConversionRate": $('#txt_conversion').val(),
"DrugForm": $("#dd_drugform option:selected").val(),
"StoredAs": $("#dd_storedas option:selected").val()
};
$.ajax({
url: '/Drug/UpdateProduct/',
type: 'POST',
data: JSON.stringify({ 'ProductData': ProductDataArray, 'ProductDetailsData': ProductDetailsDataArray }),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
// do something
}
});
});
Controller Action
[HttpPost]
public ActionResult UpdateProduct(Entity_Product ProductData, Entity_ProductDetails ProductDetailsData)
{
return Json(DrugService.UpdateProduct(ProductData, ProductDetailsData));
}
Related
My c# action looks like:
[HttpPost]
public JsonResult GetItems(int id)
{
var productsQryList = some-query-to-getitems.ToList();
if(productsQryList != null)
{
return Json(productsQryList);
} else
{
return Json(new());
}
}
In my view, the autocomplete configuration looks like:
$("#productInfo").autocomplete({
minLength: 1,
source: function( request, response ) {
$.ajax({
type: "GET",
url: "/api/purchase/SearchProductsSimple",
data: {
term: request.term
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function( data ) {
response( data );
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
select: function (event, ui) {
if (ui.item) {
$("#order-items-table tbody tr").remove();
$.ajax({
cache: false,
type: "POST",
url: "/api/purchase/GetItems",
data: { "id": ui.item.value },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (itemList) {
for(const item of itemList) {
appendOneRow(item);
counter++;
}
countTrSetIndex();
return false;
}))
},
failure: function (response) {
alert(response.d);
}
});
}
}
});
In firefox plugin RESTED,
The GetItems method runs good if I change its attribute to HttpGet.
But, if The attribute is HttpPost, I got 400 error.
By the way, The select event must be POST call.
wait for resolution.
Thank you guys.
You might have [AutoValidateAntiforgeryToken] attribute on your controller, so you must send forgery token value at ajax call.
data: { "id": ui.item.value,
"__RequestVerificationToken":$( "input[name='__RequestVerificationToken']" ).val() },
I am getting the following error when trying to load DataTables ajax sourced data:
DataTables warning: table id=report-table - Ajax error. For more information about this error, please see http://datatables.net/tn/7
Below is my DataTables html:
<table id="report-table" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</tfoot>
</table>
Below is my DataTables javascript:
$('#report-table').DataTable({
"ajax": data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
Below is the confirmed json my C# controller is returning for the DataTables ajax data:
{
"data":[
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
},
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
},
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
}
]
}
The error seems to be related to the JSON format, but not sure what is wrong?
EDIT:
Adding full javascript code:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: 'json',
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"ajax": data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>
Your <script> block should look like this to initialize your data for your Data Tables:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: "json",
method: "post",
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"data":data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>
the data source should be an array of arrays that contains the data in the tbody
say
data = [
["foo","foo","foo","foo","foo"],
["foo","foo","foo","foo","foo"],
["foo","foo","foo","foo","foo"]
];
see the example [https://datatables.net/examples/data_sources/js_array.html][1]
additionally, use data: data.data instead of "ajax" : data
As your JSON response is an object but not an array, specify the ajax to get the JsonResponse.data as below:
"ajax": {
"url": /* Your Get Data API url */,
"dataSrc": function (json) {
return json.data;
},
},
OR
"ajax": {
"url": /* Your Get Data API url */,
"dataSrc": "data"
},
JQuery answer
Updated: Change from json.data to data as Post Owner changed requirement.
data: data
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: 'json',
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"data": data,
... // Remaining DataTable configurations
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
Output
Reference
ajax - DataTables.net
I have to call a REST url for example : https://{baseurl}/employees/taxvalidation/. The Request type is JSON, but I'am always get the error Alert. I can't figure out what is the wrong in my code. I am using JQuery
The Supported HTTP Method is : PUT (HTTP PUT with correct request needs to be made) and also i need to pass a API key: XXXXX-XXXXX-XXXXX-XXXXX as request Header.
I have just have two mandatory fields in web page Employee name and Employee Tax.
I have tried the below using JQuery Ajax call.
Request Body Sample:
"name": "Company XYZ", /* mandatory */
"TAX": "*********", /* mandatory */
"taxType": "U", /* Could be E, S, or U */
"address": "2501 Boilermaker road", /* optional */
"citystatezip":"Lapalma ca 76567", /* optional */
"country": "US", //optional
"checks" : "DT",`enter code here`
"details": "DT"`enter code here` //optional
$(function() {
$("#btnSubmit").click(function() {
alert("Hi JQuery");
var URL = "https://api.dev.amx-city.com/tesmdm/dev/tesmdm/empcatalog/partners/taxvalidation/";
$.ajax({
url: URL,
headers : {
'AMX-API-KEY': '487b9474-27a6-4d21-8eda-c3a2a14e4ebe'
},
type: 'POST',
data: {
name: 'Employeename',
tin: '79847324987',
tinType: 'U'
},
dataType: 'json',
success: function(result) {
alert(result);
},
error: function (restul) {
alert(result);
}
});
});
});
when i try to hit the button the debugging is stopped till Alert, after that i don't see the URL is hitting. Let me know if i am doing any wrong?
I am able to get the response now. Below is the working script
$.ajax({
url: URL,
type: "PUT",
headers: {
'AXT-API-KEY': '48776474-26a6-4d21-8eda-c3a2a14e4ebe'
},
data: JSON.stringify({"name": "SupplierName, LLC","tin": "522323454","tinType": "U","checks": "DT"
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr);
alert(thrownError);
}
});
It worked when i use the key in beforeSend function. But i am not sure the difference.
beforeSend: function (xhr) {
xhr.setRequestHeader("AXT-API-KEY': '48776474-26a6-4d21-8eda-c3a2a14e4ebe");
Salaamun Alekum
I am getting null in controller action via an AJAX request:
var ProjectPermission = [{
"CreatedBy": "Akshay"
},{
"CreatedBy": "Kumar"
},{
"CreatedBy": "ETC"
}]
$.ajax({
url: '/api/Projects/AssignProjectPermissions',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
ProjectPermission: ProjectPermission
}),
success: function (data) {
alert(data);
},
// processData: false //Doesn't help
});
My C# controller:
[System.Web.Http.HttpPost, System.Web.Http.HttpGet]
public string AssignProjectPermissions(ProjectPermission[] ProjectPermission)
{
I am getting null in ProjectPermission. I already tried other answers but none of them worked for me. These were the posts I checked:
How to get Ajax posted Array in my C# controller?
Ajax post to ASP.net MVC controller - object properties are null
Thank You
You should not be using GET and POST on the same method first of all, just use POST in this case. That aside you do not need the property name. You are putting your array inside of an object. Your method is expecting an array.
var ProjectPermission = [{ CreatedBy: "Akshay" },
{ CreatedBy: "Kumar" },
{ CreatedBy: "ETC" }]
$.ajax({
url: '/api/Projects/AssignProjectPermissions'
, type: 'POST'
, contentType: 'application/json'
, dataType: 'json'
, data: JSON.stringify(ProjectPermission) //<------------issue here
, success: function (data)
{ alert(data); }
//, processData: false
});
I have a dynamic function to generate table data to JSON which kinda works, now I try to add it to a list in .NET however I can't get this right past few days, anybody knows what I do wrong?
the output is like this:
[{"itemsSerialized":"{\"id\":1,\"name\":\"Medical 1\",\"city\":\"Kiev\",\"instituteTypeId\":0}"},{"itemsSerialized":"{\"id\":2,\"name\":\"Medical 2\",\"city\":\"Kherson\",\"instituteTypeId\":0}"}]
which should be without the "itemsSerialized":", I understand where it comes from, but dont understand why a object declaration suddenly shows up in my JSON string
my C# code:
Object itemsSerialized = "";
foreach (DataRow r in _data.Rows)
{
DynamicClass dynamicClass = new DynamicClass();
dyna.ConvertRowToCustomer(r, out dynamicClass);
DynamicClassList.Add(dynamicClass);
var iSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
itemsSerialized = JsonConvert.SerializeObject(dynamicClass.Property.properties);
Object itemsSerialized2 = JsonConvert.DeserializeObject(xJSON);
Gridist.Add(new { itemsSerialized });
}
with jQuery I have this to load the data into the jQGrid:
$.ajax({
type: "POST",
contentType: "application/json",
url: "dataServices/objects.asmx/InvokeData",
data: "{ 'q': 'med&1'}",
dataType: 'json',
success: function (result) {
var str = result.d;
alert(result.d);
$("#jqGrid_2")[0].addJSONData(result.d);
}
});
The return I have now as:
{"id":1,"name":"Medical 1","city":"Kiev","instituteTypeId":0},{"id":2,"name":"Medical 2","city":"Kherson","instituteTypeId":0}
UPDATE INTERNAL AJAX VERSION:
mtype: 'POST',
contentType: "application/json",
url: "dataServices/objects.asmx/InvokeData",
ajaxGridOptions: {
contentType: 'application/json; charset=utf-8'
},
postData: JSON.stringify({q: "med&1"}),
loadonce: true,
dataType: 'json',
jsonReader: {
root: function (obj) {
alert(obj.d);
return obj.d;
},
page: "",
total: "",
records: function (obj) {
return obj.d.length;
},
},
gridview: true,
loadError: function (xhr, status, error) {
alert('load error: ' + error);
},
And is being written away in the first column from first and only row....
What I do wrong and how I get the itemsSerialized out
First of all the server response
{
"id": 1,
"name": "Medical 1",
"city": "Kiev",
"instituteTypeId": 0
},
{
"id": 2,
"name": "Medical 2",
"city": "Kherson",
"instituteTypeId": 0
}
is wrong. Correct data should be array of items like
[
{
"id": 1,
"name": "Medical 1",
"city": "Kiev",
"instituteTypeId": 0
},
{
"id": 2,
"name": "Medical 2",
"city": "Kherson",
"instituteTypeId": 0
}
]
Another JSON response which you posted contains two problems. 1) "itemsSerialized":" prefix 2) the value of all items are strings
[
{
"itemsSerialized": "{\"id\":1,\"name\":\"Medical 1\",\"city\":\"Kiev\",\"instituteTypeId\":0}"
},
{
"itemsSerialized": "{\"id\":2,\"name\":\"Medical 2\",\"city\":\"Kherson\",\"instituteTypeId\":0}"
}
]
The reason of the first problem is the usage of
Gridist.Add(new { itemsSerialized });
instead of
Gridist.Add(itemsSerialized);
The reason of the second problem is unneeded usage of JsonConvert.SerializeObject. What you should do is something like
Gridist.Add(dynamicClass.Property.properties);
instead of
itemsSerialized = JsonConvert.SerializeObject(dynamicClass.Property.properties);
Gridist.Add(new { itemsSerialized });