Ad

ASP.NET: POST List / Model With Ajax (JSON) From View To Controller

- 1 answer

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

  1. How to POST a List<Object> from the view with Ajax to the controller?
  2. OR How to POST a Model from the view with Ajax to 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
});
Ad

Answer

I don't know what exactly I changed to make it work but the following compiles correctly. Could be the processData: true and cache: false properties?

Controller

[HttpPost]
public JsonResult CreatePDF([FromBody] ReportViewModel model)
{
    // Lots of code
    return Json(new { isError = false });
}

View (JS only)

$.ajax({
  type: "POST",
  url: "CreatePDF",
  data: JSON.stringify(@Html.Raw(Json.Serialize(Model))),
  contentType: 'application/json; charset=utf-8',
  processData: true,
  cache: false,
  // Code for success and error
});
Ad
source: stackoverflow.com
Ad