Working in ASP.NET Core where I'm trying to POST a List of Items through Ajax. Ideally, I would like to pass the entire ReportViewModel but I haven't been able to match the signature correctly (since passing a DateTime or a List isn't that easy).
My question
- How to
POSTaList<Object>from the view withAjaxto the controller? - OR How to
POSTaModelfrom the view withAjaxto the controller?
I currently have the following code:
Models
public class ReportViewModel {
public int ReportType { get; set; };
public DateTime DateFrom { get; set; };
public DateTime DateTo { get; set; };
public List<Item> ItemList{ get; set; };
}
public class Item {
// Properties are simple types
}
View (ReportView)
@model Namespace.ViewModels.ReportViewModel
@inject Namespace.Resource Resources
<!-- HTML code -->
<form>
<button class="ui button" type="submit" onclick="return createPDF();">@Resources.Save</button>
</form>
<script>
function createPDF() {
alertify.set('notifier', 'position', 'bottom-left');
$.ajax({
type: "POST",
url: "CreatePDF",
data: JSON.stringify({
reportType: @Model.ReportType,
ticksDateFrom: @Model.DateFrom.Ticks,
ticksDateTo: @Model.DateTo.Ticks
@* TODO: Add the List<Items> itemList (from @Model.ItemList)*@
}),
contentType: 'application/json',
// Code for success and error
});
return false;
};
</script>
Controller (ReportController)
[HttpPost]
public JsonResult CreatePDF([FromBody] dynamic data) {
// Lots of code
return Json(new { isError = false });
}
/* When passing the entire model
* [HttpPost]
* public JsonResult CreatePDF([FromBody] ReportViewModel model) {
* // Lots of code
* return Json(new { isError = false });
* }
*/
I tried passing the model as seen below but that leaves me with the parameter in the controller being null or as a new "empty" object, depending if I use [FromBody] or not.
$.ajax({
type: "POST",
url: "CreatePDF",
data: @Html.Raw(Json.Serialize(Model)),
contentType: 'application/json',
// Code for success and error
});
data: JSON.stringify( { model: @Html.Raw({ Json.Serialize(Model)) }),where the parameter isReportViewModel model)Json.Serialize(Model)does), not anything that has been modified :)