在ASP.NET Core
中工作,我正在尝试从Items
到Ajax
的POST
和List
。理想情况下,我想传递整个ReportViewModel
,但我无法正确匹配签名(因为传递DateTime
或List
并不那么容易(。
我的问题
- 如何用
Ajax
将视图中的POST
和List<Object>
连接到控制器 -
OR如何将
POST
和Model
从带有Ajax
的视图连接到控制器
我目前有以下代码:
型号
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>
控制器(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 });
* }
*/
我尝试传递如下所示的模型,但控制器中的参数为null
或作为一个新的"空"对象,这取决于我是否使用[FromBody]
。
$.ajax({
type: "POST",
url: "CreatePDF",
data: @Html.Raw(Json.Serialize(Model)),
contentType: 'application/json',
// Code for success and error
});
您可以在视图中使用发布到控制器的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>
}
然后你就不再需要JavaScript了,另一件需要记住的事情是尽可能多地在服务器端保留功能。
如果您将表单POST到控制器,您可以访问视图的参数等,如下所示:
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:(
我不知道我到底做了什么更改以使其工作,但以下内容编译正确。可能是processData: true
和cache: false
属性?
控制器
[HttpPost]
public JsonResult CreatePDF([FromBody] ReportViewModel model)
{
// Lots of code
return Json(new { isError = false });
}
视图(仅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
});