Ajax Not Working With C# Controller Action With 2D Array Parameter - javascript

My Ajax is not hitting my controller action. What could be the reason?
My Controller Action
public ActionResult Save_Data(string [][] rosterArray, int Pricelist_Id, int Group_Id)
My Ajax
$.ajax({
url: '#Url.Action("Save_Data", "PriceListMaster")',
type: 'Post',
async: false,
contentType: 'application/json',
dataType: "json",
data: { "rosterArray": rosterArray, "Pricelist_Id": "2", "Group_Id": $("#Group_Id").val() },
//data: JSON.stringify({ "Item_Code": Item_Code, "IPD_Price": IPD_Price, "OPD_Price": OPD_Price, "EMS_Price": EMS_Price }),
success: function (data) {
debugger
if (data.success)
{
alert('Data Saved Successfully.');
location.reload();
} else {
alert(data.error_msg);
}
}
}

If you are using type: 'Post' in AJAX, that means you need to add a Request type in Controller.
Try using this in controller,
[HttpPost]
public ActionResult Save_Data(string [][] rosterArray, int Pricelist_Id, int Group_Id)
Use httpPost in the Method for define type of response.

at client side
$.ajax({
url: '#Url.Action("Save_Data", "PriceListMaster")',
type: 'Post',
async: false,
contentType: 'application/json',
dataType: "json",
data: { "rosterArray": JSON.stringify(rosterArray), "Pricelist_Id": "2", "Group_Id": $("#Group_Id").val() },
//data: JSON.stringify({ "Item_Code": Item_Code, "IPD_Price": IPD_Price, "OPD_Price": OPD_Price, "EMS_Price": EMS_Price }),
success: function (data) {
debugger
if (data.success)
{
alert('Data Saved Successfully.');
location.reload();
} else {
alert(data.error_msg);
}
}
}
and your controller code can be like this:
[HttpPost]
public ActionResult Save_Data(string rosterArray, int Pricelist_Id, int Group_Id)
{
string [][] convertedArray = JsonConvert.DeserializeObject<string [][]>(rosterArray);
}
Hope this works
Note: But you need to incude using Newtonsoft.Json;

Related

ASP.NET Core MVC controller receives null for input parameter from ajax call

I have an ajax call:
...
$("#testBtn").click(function (e) {
e.preventDefault();
$.ajax({
url: "/profile/GuestList",
data: {"keytype": "1"},
method: "POST",
contentType: "application/json",
success: function (data) {
...
}
});
});
...
and my controller method:
[HttpPost]
public async Task<IActionResult> GuestList([FromBody]string keytype)
{
try
{
return Ok();
}
catch (Exception ex)
{
}
}
So, inititally I wanted to send an enum type, but that didnt work, so I wanted to send an int with value 1 and I kept getting only 0, then I added [FromBody] and it was the same, at last I switched to string just in case, and now Im getting a null value.
Where I went wrong in all this variations?
Create class
public class KeyTypeViewModel
{
public string Keytype { get; set; }
}
Fix action by removing [FromBody]
[HttpPost]
public async Task<IActionResult> GuestList(KeyTypeViewModel viewModel)
And fix ajax by removing contentType: "application/json" :
$.ajax({
url: "/profile/GuestList",
data: {keytype: "1"},
method: "POST",
success: function (data) {
...
}
You need to create a Dto that has property keytype.
public class SomeDto
{
public string Keytype { get; set; }
}
[HttpPost]
public async Task<IActionResult> GuestList([FromBody]SomeDto dto)
You have to update your data in your Ajax call to a string as you are using string as input parameter in your POST method.
...
$("#testBtn").click(function (e) {
e.preventDefault();
$.ajax({
url: "/profile/GuestList",
data: "1",
method: "POST",
contentType: "application/json",
success: function (data) {
...
}
});
});
...
You must stringify your data.
Try the following:
$.ajax({
url: "/profile/GuestList",
data: JSON.stringify({"keytype": "1"}),
method: "POST",
contentType: "application/json",
success: function (data) {
...
}
});

How do I pass a JSON object from ajax to ASP.net page

I have the following code that sends JSON objects to a MVC controller through POST, I have no idea why its not working, any suggestions?
JS
function Update()
{
var objects = $(".Classes");
items = [];
objects.each(function () {
items .push({
"Id": $(this).find(".input").attr('id'),
"Value": $(this).find(".input2").val()
});
});
$.ajax({
type: "POST",
url: "/A/Update",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(items),
contentType: "application/json",
dataType: "json",
success: function (response) {
}
});
}
Model
public class Update{
public string Id{get;set;}
public string Value{ get; set; }
}
Task
[HttpPost("Update")]
public async Task<JsonResult> Update(IList <Update> items)
{...}
The task runs but JSON objects never deserialize to the model, I always get items of count 0.
you must be change your code data:{"items":JSON.stringify(items)} because you must be send Post data name
then change code to this code
function Update()
{
var objects = $(".Classes");
items = [];
objects.each(function () {
items .push({
"Id": $(this).find(".input").attr('id'),
"Value": $(this).find(".input2").val()
});
});
$.ajax({
type: "POST",
url: "/A/Update",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data:{"items":JSON.stringify(items)},
contentType: "application/json",
dataType: "json",
success: function (response) {
}
});
}
The only change is to use [FromBody] to let model binding system read post data from request body and bind to your object :
public async Task<JsonResult> Update([FromBody]IList<Update> items)

How to httppost a list of objects?

I have this list of objects which I need to send from my angularjs javascript code:
var dataToSend = [{
SubId: "c9cb1d3e-8c32-4a9e-8f0d-0008196776de",
CustomerName: "Blah"
}, {
SubId: "aaaa1d3e-8c32-4a9e-8f0d-0008196776de",
CustomerName: "Blah2"
}]
I've tried these different variations but none of them are working:
1.
$http.post("url",
{
dataType: 'json',
headers: {
contentType: "application/json; charset=utf-8",
},
method: "POST",
data: dataToSend,
}).then...
2.
$http.post("url",
{
data: $.param(dataToSend),
}).then...
3
$http.post("url",
{
data: angular.toJson(dataToSend),
}).then...
4
$http.post("url",
{
data: { customers: dataToSend },
}).then...
5
$http.post("url",
{
data: JSON.stringify({ customers: dataToSend }),
}).then...
My API side code is (I have tried with [FromBody] attribute but no luck there):
[HttpPost]
public async Task<JsonResult> CreateCustomers(List<Customer> customers)
{
// customers is always null
}
And this is my Customer.cs:
public partial class Customer
{
public System.Guid SubId { get; set; }
public string CustomerName { get; set; }
}
Can you please help me? I have tried posting to CreateCustomers(Customer c) without using a list and its working as expected. But when I use a list, its always coming as null on the other side.
EDIT:
$.ajax is working but $http.post isn't. Any idea why?
var request = $.ajax({
dataType: "json",
url: "url",
method: "POST",
data: { '': dataToSend }});
Are you sending JSON ( Include dataType: 'json')
$http({
url: "url",
dataType: 'json',
method: 'POST',
data: dataToSend,
headers: {
contentType: "application/json; charset=utf-8",
}
})
In C# add FromBody in parameter
[HttpPost]
public async Task<JsonResult> CreateCustomers([FromBody]]List<Customer> customers)
{
// customers is always null
}
More on Ajax parameters
contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.
dataType is what you're expecting back from the server: json, html, text, etc.
This should work. post full code if you face issue
use [ModelBinder] in front of your param.
[HttpPost]
public async Task<JsonResult> CreateCustomers([ModelBinder]List<Customer> customers)
{
// customers is always null
}
Web API only uses model binding for simple types, falling back on formatters for everything else. Adding [ModelBinder] forces the complex types to use model binding anyway.
Your post data is not matched with the parameter List<Customer>.
Change your server side method to something like:
[HttpPost]
public async Task<JsonResult> CreateCustomers(JObject queryParam)
{
// populate your list here
// for eaxample : var customers = queryParam["customers"].ToString();
}
And also you can use this code to send data to the server:
$http({
url: 'url',
dataType: 'json',
method: 'POST',
data: jsonData,
headers: { "Content-Type": "application/json" }
}).success(function(response){ $scope.response = response;
}).error(function(error){ $scope.error = error; });

Submitting Ajax request from external javascript file in ASP.NET MVC

I am trying to submit an ajax request from an external JavaScript file in ASP.NET MVC. I'm getting a 500. What am I doing wrong?
Ajax call (From external JS file)
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: { jsonData: "testing" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
Controller Action Method (That should be catching the request)
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpGet]
public void AjaxEndpoint()
{
var thing = 1 + 2;
}
// AJAX endpoint for GetProducts.js
[HttpPost]
public void AjaxEndpoint(string jsonData)
{
var thing = 1 + 2;
}
}
Error I'm getting
You either need to remove the contentType option
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: { jsonData: "testing" },
dataType: "json",
success: successFunc,
error: errorFunc
});
or alternatively, stringify the data
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: JSON.stringify({ jsonData: "testing" }),// modify
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
Your ajax call needs to be to an ActionResult in the controller, The controller performs and returns the data to the page
[HttpPost]
public ActionResult ajaxcall(string ids)
{
String Data = code to perform
return Json(Data);
}
this is the basic idea. Javascript makes the call and uses the json data returned on the clients page

Null value when passing value from ajax to MVC controller

I have a value that I want to pass to MVC action,
here is the JS side
function functionName(Name) {
$.ajax({
url: "/Home/GetName",
type: "POST",
dataType: "json",
data:JSON.stringify({
Name: Name
}),
success: function (mydata) {
}
});
return false;
}
and here is my action
[HttpPost]
public JsonResult GetName(string Name)
{
return Json(new { oid = Name});
}
Noting that I successfully print the value "Name" before I send it to the action, but the action is receiving it as a "null"
Stephen "in the comments" is correct
the solution is
changing this
data:JSON.stringify({
Name: Name
}),
to
data: { Name: Name }
Try by adding
contentType: "application/json"
as belove
function functionName(Name) {
$.ajax({
url: "/Home/GetName",
type: "POST",
dataType: "json",
contentType: "application/json",
data:JSON.stringify({
Name: Name
}),
success: function (mydata) {
}
});
return false;
}
Hope this will help you, :)

Categories