Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things });
Here is the complete code.
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/PassThings',
data: things,
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
public void PassThings(List<Thing> things)
{
var t = things;
}
public class Thing
{
public int Id { get; set; }
public string Color { get; set; }
}
There are two things I learned from this:
The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error.
To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.
I hope this helps someone else!
pass a list of objects via ajax to a MVC controller always sends null
This is a new answer. Originally, I was getting null, like you. But, now it works the way you want (array of complex objects). Please get this to work for you. If you can't get it to work, although it should, I can create an ASP.NET Fiddle.
public class RecievedTransactions
{
public int numReceived { get; set; }
public int transactionID { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public void ReceivePOLines(List<RecievedTransactions> inTransactions) // MyArray MyArray
{
return;
}
//you use your own action name
public ActionResult Tut133()
{
return View();
}
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut132</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
var items = [];
$('#grid tr').each(function () {
var item = {};
item.numReceived = $(this).find("input[id*='NumReceived']").val();
/*skip the header row*/
if (item.numReceived !== null) {
item.transactionID = $(this).find("input[id*='item_TransactionID']").val();
items.push(item);
}
});
$.ajax({
//!!changing your url
//url: './ReceivePOLines',
url: "/Home/ReceivePOLines",
type: "Post",
cache: false,
//data: JSON.stringify({ MyArray: items }),
data: JSON.stringify(items),
//expecting back from server-need to remove since we are not getting back data from server
//dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function () {
//alerting success instead of opening window
alert("success");
//window.location.replace("../Home/Index");
},
error: function (request) {
alert("error");
}
});
})
</script>
</head>
<body>
<table id="grid">
<tr>
<td><input type="text" id="NumReceived1" value="10000" /></td>
<td><input type="text" id="item_TransactionID1" value="10661768" /></td>
</tr>
<tr>
<td><input type="text" id="NumReceived2" value="10000" /></td>
<td><input type="text" id="item_TransactionID2" value="10661769" /></td>
</tr>
</table>
<input type="button" id="theButton" value="Go" />
</body>
</html>
Passing A List Of Objects Into An ActionResult MVC Controller Method Using jQuery Ajax
I think first of all your JSON should be strongly typed.
and once it already strongly typed you need not use JSON.stringfy.
instead go with,
data: {"things" : things},
and your controller should be like
public IActionResult ActionName(List<Model> things)
Passing List of objects to ASP.Net Core MVC controller using jQuery AJAX
You should use [FromBody]
to get list object in controller side.
Also you fill item
object twice therefore itemTwo
object becomes null.
var divisions=[];
var item = {};
item.DivisionName ="polo"
item.DivisionId = 1;
item.UpdatedOn = null;
divisions.push(item);
var itemTwo = {};
itemTwo.DivisionName ="polo2"
itemTwo.DivisionId = 2;
itemTwo.UpdatedOn = null;
divisions.push(itemTwo);
public IActionResult Save([FromBody]List<DivisionDetails> divisions)
{
var result = _divisionService.Save(divisions);
return Json(result);
}
jQuery Ajax cannot send List of objects to MVC controller
Start by writing a view model that will encapsulate the needed parameters:
public class MyViewModel
{
public int ParamReferenceNo { get; set; }
public List<SalesProd_Lots> ParamLots { get; set; }
}
which your controller action will take as parameter:
public void Save_Lots(MyViewModel viewModel)
{
...
}
and then on the client side:
paramReferenceNo = 2;
lots = paramLots; // this could be a complex object
$.ajax({
contentType: 'application/json; charset=utf-8',
type: 'POST',
url: serverpath + '/Home/Save_Lots',
data: JSON.stringify({
paramReferenceNo: paramReferenceNo,
paramLots: lots
},
success: function (data) {
alert('Saved!');
}
});
How to pass list of object to method by ajax MVC
Try to initialize your detail with object rather then array:
const saveDetail = []; // wrong
const saveDetail = {}; // correct
see this page for reference
Pass array of objects to MVC Controller Action via JQuery AJAX, Action Parameter is always null
Your action parameter is null
because you have to fix the way you are sending the data property from your ajax to this:
$.ajax({
type: "POST",
url: serviceURL,
data: JSON.stringify({ 'lstmixing': DATA }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {...
And finally you have another possible problem when inserting the data in the array. I mean this line:
DATA.push("{'MIXINGNO':'" + MIXINGNO + "','DATE': '" + DATE + "','INVOICEDETAILID': '" + INVOICEDETAILID + "','CARET': '" + CARET + "','PRICE': '" + PRICE + "','DETAILS': '" + DETAILS + "'}");
You are trying to insert into the array objects like they already are objects type JSON, the way you have to do this is inserting them like javascript normal objects, like this:
DATA.push({
MIXINGNO: MIXINGNO,
DATE: DATE,
INVOICEDETAILID: INVOICEDETAILID,
CARET: CARET,
PRICE: PRICE,
DETAILS: DETAILS
});
Related Topics
What Could Cause an Assignment to Not Work
How to Round Up the Time to the Nearest X Minutes
How to Use Telegram API in C# to Send a Message
Add Header and Footer for Pdf Using Itextsharp
Asp.Net Core Localization Decimal Field Dot and Comma
C# String to Hex , Hex to Byte Conversion
Split a Comma-Separated String With Both Quoted and Unquoted Strings
Reading from Excel File Using Closedxml
Passing a List of Objects into an MVC Controller Method Using Jquery Ajax
How to Combine Values of Several Lists into One in C#
How to Get Number of Rows Using Sqldatareader in C#
Removing Text Between 2 Strings
Searching If Value Exists in a List of Objects Using Linq
How to Determine If a Json Object Contains Only a Specific Key
How to Get the List of Properties of a Class
Automapper - Map Using the Same Source and Destination Object Types