Receving null value in controller action via AJAX - c#

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
});

Related

Call the REST API url using asp.net / JQuery Ajax

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");

Data received in controller from ajax is NULL?

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));
}

Passing arguments in jQuery post to a method in controller

In ASP.NET MVC I was using this script to call a method in controller:
<script>
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: "2",
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});
</script>
and this is the method I call:
public async Task getBookedByUser(string id)
{
BenchesService benchService = new BenchesService();
List<Bench> obj = await benchService.getLastBenchByUser(id);
userBench = obj.ElementAt(0);
}
My problem is that id in my controller method is null. It doesn't assume the value "2" as I intend.
Any idea why?
You're almost there. You need to setup the JSON to include your id property:
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: { id: '2' },
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});

Ajax not posting data to controller

I am posting data through ajax to a action, but the problem I am not able to get the data posted through ajax in my controller action. While debugging, the call gets transferred to action but I dont get anything in data not even 'null'.
here is my ajax call,
$.ajax({
type: 'POST',
url:' #Url.Action("PostAmount", "Deal")',
data: { country: 2, amount: 4.02 },
datatype:JSON,
success: function (data) {
alert("hiiii"+data);
}
});
and my action,
[HttpPost]
public JsonResult PostAmount(int country,double amount)
{
AllocationViewModel mod = new AllocationViewModel();
return Json(mod);
}
Try this:
var dataToPost = "{ country:'" + 2 + "', amount:" + 4.02 + "}";
$.ajax({
url: #Url.Action("PostAmount", "Deal")',
type: "POST",
dataType: 'json',
data: dataToPost,
cache: false,
contentType: "application/jsonrequest; charset=utf-8",
success: function (data) {
alert("hi"+ data);
}
});
try the following:
$.ajax({
type: 'POST',
url:' #Url.Action("PostAmount", "Deal")',
data: { "country": "2", "amount": "4.02" },
datatype:JSON,
success: function (data) {
alert("hiiii"+data);
}
});
or the best solution is to save the values in an object and use the jquery function "stringify" and then send the values over. that should work.
try putting json in quotes
$.ajax({
type: 'POST',
url:'#Url.Action("PostAmount", "Deal")',
data: { country: "2", amount: "4.02" },
dataType:"json",
traditional:true,
success: function (data) {
alert("hiiii"+data);
}
});
You could also use JSON.stringify(yourObject) on your object to make it a JSON object. This makes it easier to create objects in javascript and pass then into the data parameter of your post request.
Also use a string for the datatype parameter (https://api.jquery.com/jquery.post/), as suggested in the answers above.
var dataToPost = { country: 2, amount: 4.02 };
$.ajax({
type: 'POST',
url:' #Url.Action("PostAmount", "Deal")',
data: JSON.stringify(dataToPost),
datatype: 'json',
success: function (data) {
alert("hiiii"+data);
}
});
The other way around is JSON.parse(yourJsonObject). This way you can parse a JSON string into a Javascript object.

List of GUIDs JSON being sent to MVC controller via GET is empty upon arrival, POST works

I am sending a collection of GUID-like objects to my MVC controller like so:
$.ajax({
type: 'GET',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: {
songIds: JSON.stringify(songIds)
},
success: function (data) {
},
error: function(error) {
console.error(error);
}
});
The data being sent in my request header looks like:
songIds:["6cb44f55-9fd5-4540-9b11-75ccce816d67"]
and my MVC3 controller method looks like:
[HttpGet]
public ActionResult GetByIds(List<Guid> songIds)
{
SongManager songManager = new SongManager(SongDao, PlaylistDao, PlaylistItemDao);
IList<Song> songs = songManager.GetByIds(songIds);
return new JsonDataContractActionResult(songs);
}
In this implementation I receive a non-null List object, but it is always empty. What's my mistake?
EDIT: If I POST like this instead of GET it works fine. How come??
$.ajax({
type: 'POST',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
songIds: songIds
}),
success: function (data) {
loadedSongs = loadedSongs;
if (callback) {
callback(data);
}
},
error: function(error) {
console.error(error);
}
});
You should try to use "traditional" option set to true for your jQuery Ajax request.
Refer to documentation for more details : http://api.jquery.com/jQuery.ajax/
And you should also remove the JSON.Stringify part.
Can you try this out and let me know if it worked out for you ?
I Did a test on my end and it works just fine.
$.ajax({
type: 'GET',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
traditional: true, //// traditional option to true
data: {
songIds: songIds /// no JSON.stringify
},
success: function (data) {
},
error: function(error) {
console.error(error);
}
});

Categories

Resources