简体   繁体   English

ASP.NET:开机自检列表 <Object> /使用Ajax(JSON)从视图到控制器进行建模

[英]ASP.NET: POST List<Object> / Model with Ajax (JSON) from view to controller

Working in ASP.NET Core where I'm trying to POST a List of Items through Ajax . 在工作ASP.NET Core在那里我想POST一个ListItems通过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). 理想情况下,我想传递整个ReportViewModel但是我无法正确匹配签名(因为传递DateTimeList并不那么容易)。

My question 我的问题

  1. How to POST a List<Object> from the view with Ajax to the controller? 如何POST一个List<Object>从与所述视图Ajax到控制器?
  2. OR How to POST a Model from the view with Ajax to the controller? 如何POST一个Model从视图Ajax到控制器?

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) 查看(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) 控制器(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. 我尝试传递模型,如下所示,但这使控制器中的参数为null或作为新的“空”对象,这取决于我是否使用[FromBody]

$.ajax({
  type: "POST",
  url: "CreatePDF",
  data: @Html.Raw(Json.Serialize(Model)),
  contentType: 'application/json',
  // Code for success and error
});

You can use the BeginForm in your view that posts to a controller: 您可以在发布到控制器的视图中使用BeginForm:

@model Namespace.ViewModels.ReportViewModel
@inject Namespace.Resource Resources

@using (Html.BeginForm("CreatePDF", "[PDFControllerName]", FormMethod.Post, new { @id = "pdfCreatorForm" }))
{
    <!-- Send parameters to a controller like this (invisibly) -->
    @Html.HiddenFor(m => m.ReportType)
    @Html.HiddenFor(m => m.DateFrom.Ticks)
    @Html.HiddenFor(m => m.DateTo.Ticks)
    @Html.HiddenFor(m => m.ItemList) <!-- Send the List<Items> -->

    <button type="submit" class="ui button" onclick="alertify.set('notifier', 'position', 'bottom-left')">@Resources.Save</button>
}

And then you don't need the JavaScript any more, another thing to keep in mind is to keep as much functionality on your server side as you can. 然后,您不再需要JavaScript,需要牢记的另一件事是在服务器端保留尽可能多的功能。

If you POST the form to a controller, you can access the view's parameters etc like this: 如果将表单发布到控制器,则可以像下面这样访问视图的参数:

public JsonResult CreatePDF(ReportViewModel formData)
{
    int reportType = formData.ReportType;
    DateTime ticksDateFrom = formData.DateFrom.Ticks;
    DateTime ticksDateTo = formData.DateTo.Ticks;
    List<Items> itemList = formData.ItemList;

    // Lots of code
}

And, you actually doesn't need to specify that it's taking in a HttpPost :) 而且,您实际上不需要指定它接受HttpPost :)

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? 可能是processData: truecache: false属性吗?

Controller 调节器

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

View (JS only) 查看(仅JS)

$.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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM