gpt4 book ai didi

javascript - ASP.NET:使用 Ajax (JSON) 从 View 到 Controller POST List/Model
转载 作者:行者123 更新时间:2023-12-03 01:25:47 39 4
gpt4 key购买 nike

工作于ASP.NET Core我正在尝试POST一个ListItems通过Ajax 。理想情况下,我想传递整个 ReportViewModel但我无法正确匹配签名(因为传递 DateTimeList 并不那么容易)。

我的问题

  1. 如何POST一个List<Object>从 View Ajax到 Controller ?
  2. 如何POST一个Model从 View Ajax到 Controller ?

我目前有以下代码:

模型

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
}

查看(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 });
* }
*/

我尝试传递模型,如下所示,但这使 Controller 中的参数为 null或者作为一个新的“空”对象,取决于我是否使用 [FromBody]或不。

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

最佳答案

您可以在 View 中使用 BeginForm 来发布到 Controller :

@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>
}

然后您就不再需要 JavaScript,另一件事要记住的是在服务器端保留尽可能多的功能。

如果将表单发布到 Controller ,您可以访问 View 的参数等,如下所示:

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
}

而且,您实际上不需要指定它正在接受 HttpPost :)

关于javascript - ASP.NET:使用 Ajax (JSON) 从 View 到 Controller POST List<Object>/Model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51553915/

39 4 0