【发布时间】:2021-06-29 18:55:24
【问题描述】:
所以我有这个 ajax POST,它通过对象列表(RaffleTicketNumberModel)作为属性传递一个对象,如下所示:
// id comes as parameter to this function
const TicketNumbers = localStorage.getItem(id);
const numbers = JSON.parse(TicketNumbers);
const dataToSend = {
RaffleTicketId: null,
RaffleScheduleId: scheduleId,
UserId: user,
DatePaid: new Date().toISOString(),
Status: true,
Active: true,
AmountPaid: amountPaid,
UserModel: null,
RaffleScheduleModel: null,
RaffleTicketNumberModel: numbers
};
$.ajax({
type: 'POST',
url: 'RaffleSellsPage?handler=CreateRaffleTicket',
contentType: 'application/json',
beforeSend: function (xhr) {
xhr.setRequestHeader('XSRF-TOKEN',
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(dataToSend)
}).then(function () {
// ...
});
它成功地命中了处理程序,但问题是在 razor 页面处理程序 (dataToSend) 中获取它的参数总是为空。这是我的页面类和处理程序:
using ApiAccess;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace Tiempos_FE.Pages.Vendor.Sells
{
public class RaffleSellsPageModel : PageModel
{
[BindProperty]
public ApiAccess.RaffleTicketModel RaffleTicket { get; set; }
readonly RaffleTicketClient raffleTicketClient = new(new HttpClient());
public void OnGet()
{
}
public JsonResult OnPostCreateRaffleTicket(RaffleTicketModel dataToSend)
{
var result = dataToSend;
return new JsonResult(result);
}
}
}
我在网上尝试了几种解决方案,但它们似乎都不适合我,例如将数据附加到请求正文并使用 [FromBody] RaffleTicketModel dataToSend 检索它,并将对象作为完整字符串传递和接收,方法是替换contentType: 'text/plain' 的 Ajax contentType,但仍然为空
如下图所示,ASP.Net Core 没有将模型与参数对象绑定(只要我知道 ASP.Net Core 会这样做):
这是我的请求负载:
我做错了什么或错过了什么?非常感谢您的帮助。
注意事项:
- 请注意,我正在传递导航属性为 null 的对象(使用实体框架)这会影响它吗?
在 RaffleTicketnumbers 的属性 amoutPaid 中也有一个小错字,但模型有相同的错字,所以它应该也能正常工作。我将包括模型
仅供参考:
public class RaffleTicketModel
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int RaffleTicketId { get; set; }
[ForeignKey("RaffleSchedule")]
public int RaffleScheduleId { get; set; }
[ForeignKey("UserModel")]
public string UserId { get; set; }
[Required]
public DateTime DatePaid { get; set; }
[Required]
public bool Status { get; set; }
[Required]
public bool Active { get; set; }
[Required]
public double AmountPaid { get; set; }
public UserModel UserModel { get; set; }
public RaffleScheduleModel RaffleScheduleModel { get; set; }
public ICollection<RaffleTicketNumberModel> RaffleTicketNumberModel { get; set; }
}
【问题讨论】:
-
您的页面类(以及页面处理程序)是什么样的?这很重要,因为它与您设置模型绑定的方式有关。
-
因为是通过请求体发送json,所以需要使用
FromBodyAttribute来装饰handler的参数像这样[FromBody] RaffleTicketModel dataToSend -
我又试了一次,没有命中处理程序,我将Ajax属性
data更改为body,它命中了处理程序,但参数仍然为空 -
当它没有命中handler时,你能不能看一下窗口Output,看看那里打印的有没有错误?
-
你可以尝试不设置
contentType: 'application/json',,用小写字母将const dataToSend = {}中的所有属性写入并将INT 属性设置为0(不是NULL,因为您将它们定义为INT,而不是可以为空)
标签: ajax asp.net-core razor-pages