I’m trying to pass an array of objects into an asp .net core controller method using jQuery’s ajax() function. When I enter the exporttocsv() C# controller method, the argument "data" is null. I’ve tried this using a type of List for the argument, but that doesn’t work either. What am I doing wrong?
//model=[{
"grantNumber": "1R01MD018293-01",
"award": 731899,
"awardCode": "R01",
"awardDate": "2023-03-18T12:03:00",
"startDate": "2023-03-18T00:00:00",
"endDate": "2027-11-30T12:11:00",
"fiscalYear": 2023,
"projectTitle": "Epigenetic aging,",
"abstract": "PROJECT ABSTRACT",
"thesaurus": "37 weeks gestation;Acceleration;Address;",
"organization": "UNIVERSITY OF CENTRAL FLORIDA",
"department": "NONE",
"address": "ORLANDO,FL,UNITED STATES-328263231",
"city": "ORLANDO",
"state": "FL",
"zip": "328263231",
"country": "UNITED STATES",
"contactFirstName": "CARMEN",
"contactLastName": "GIURGESCU",
"contactTitle": "PROFESSOR, ASSOCIATE DEAN FOR RESEARCH",
"contactEmail": "",
"phone": "",
"fax": "",
"awardType": "1",
"kw": "",
"hits": 0,
"labUrl": ""
},
{
"grantNumber": "1R01AI168182-01A1",
"award": 759454,
"awardCode": "R01",
"awardDate": "2023-03-17T12:03:00",
"startDate": "2023-03-17T00:00:00",
"endDate": "2028-02-29T12:02:00",
"fiscalYear": 2023,
"projectTitle": "Influence of the nasal microbiome on host susceptibility and response to respiratory viruses",
"abstract": "PROJECT SUMMARY",
"thesaurus": "2019-nCoV;",
"organization": "GEORGE WASHINGTON UNIVERSITY",
"department": "PUBLIC HEALTH & PREV MEDICINE",
"address": "WASHINGTON,DC,UNITED STATES-200520042",
"city": "WASHINGTON",
"state": "DC",
"zip": "200520042",
"country": "UNITED STATES",
"contactFirstName": "CINDY",
"contactLastName": "LIU",
"contactTitle": "ASSISTANT RESEARCH PROFESSOR",
"contactEmail": "",
"phone": "",
"fax": "",
"awardType": "1",
"kw": "",
"hits": 0,
"labUrl": ""
}
]
<script type="text/javascript">
function check() {
debugger
var model = @Html.Raw(Json.Serialize(@ViewBag.alldata));
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: "/Home/exporttocsv",
data: { "data": JSON.stringify(model) },
type: 'POST',
success: function (data) {
location.href = '@Url.Action("DownloadCSV", "Home")?success=' + data;
}
});
};
</script>
public class HomeController: Controller
{
[HttpPost]
public string exporttocsv(List<ShowNihSearchData> data)
{
// do stuff with data here...
}
}
3
Answers
it is working fine after I change
List<ShowNihSearchData>
to the stringThere is a model binding mismatch. The "exporttocsv" action expects a list of objects. You are sending it an object with the key "model", which has a string value which is a list of objects (or something, I don’t know what ViewBag.alldata contains). You are also first JSON-stringifying the model into JSON, and then JSON.stringifying that a second time, which may or may not be what you want.
The structure of the information must match on both sides.
If your
ShowNihSearchData
is right, ajax with below code will work.