You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8 Razor Page中Ajax POST请求方法绑定失败求助

问题描述

通过Ajax向后端处理方法传递日期和ConsumerId,但后端方法始终接收到null,怀疑问题出在日期格式上。

客户端代码

consumer2.ConsumerId
var v1 = new Date();
var date = v1.getDate()+ "/" + (v1.getMonth() + 1) + "/" + v1.getFullYear();

// consumer2.datelocal = date;
console.log(consumer2);
console.log("------");
console.log(consumer);

$.ajax({
          type: 'POST',
          url: getRootPath() + '/AjaxHandlers/Details?handler=UpdateConsumer2',
          headers: {
              'RequestVerificationToken': token
          },
            data: JSON.stringify(consumer2),
         // data: JSON.stringify({ Consumer: consumer2, UpdateConsumer: PartyUpdate, ChannelOfContactibility: "MAIL" }),
         // data: JSON.stringify( consumer ),
         contentType: 'application/json; charset=utf-8',
});

服务端代码

public class Consumer2
{
     public Nullable<DateTime> datelocal { get; set; }
     public int ConsumerId { get; set; }
}

public IActionResult OnPostUpdateConsumer2([FromBody] Consumer2 consumer) 
{
    return null;
}
问题分析
  1. 日期格式不兼容:客户端手动拼接的DD/MM/YYYY格式,不符合.NET Core默认的JSON日期解析规则(默认仅支持ISO 8601格式,如YYYY-MM-DDTHH:mm:ss),导致日期解析失败,进而触发整个对象绑定失败,后端接收到null。
  2. 字段未赋值:客户端代码中consumer2.datelocal = date;被注释,导致datelocal字段未传入请求体,这也是后端接收null的直接原因之一。
解决方案

方案1:传递标准ISO 8601日期格式

直接使用JavaScript Date对象的toISOString()方法生成符合解析要求的日期字符串,无需手动拼接:

var v1 = new Date();
// 取消注释并赋值标准格式日期
consumer2.datelocal = v1.toISOString(); // 生成如"2024-05-20T14:30:00.000Z"的格式

$.ajax({
    type: 'POST',
    url: getRootPath() + '/AjaxHandlers/Details?handler=UpdateConsumer2',
    headers: {
        'RequestVerificationToken': token
    },
    data: JSON.stringify(consumer2),
    contentType: 'application/json; charset=utf-8',
    // 建议补充回调逻辑
    success: function(res) {
        console.log("更新成功");
    },
    error: function(xhr) {
        console.error("请求失败:", xhr.responseText);
    }
});

方案2:后端配置支持自定义日期格式

如果必须使用DD/MM/YYYY格式,可在后端配置JSON序列化器以支持该格式:

全局配置(.NET Core)

在Program.cs中添加全局JSON配置:

builder.Services.AddControllersWithViews()
    .AddJsonOptions(options =>
    {
        // 忽略大小写匹配字段
        options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
        // 添加自定义日期转换器
        options.JsonSerializerOptions.Converters.Add(new CustomDateTimeConverter());
    });

// 自定义日期转换器实现
public class CustomDateTimeConverter : JsonConverter<DateTime?>
{
    private readonly string _dateFormat = "dd/MM/yyyy";

    public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.String && 
            DateTime.TryParseExact(reader.GetString(), _dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result))
        {
            return result;
        }
        return null;
    }

    public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value?.ToString(_dateFormat));
    }
}

单独字段配置

若仅需针对datelocal字段处理,可直接在实体类字段上添加特性:

public class Consumer2
{
    [JsonConverter(typeof(CustomDateTimeConverter))]
    public Nullable<DateTime> datelocal { get; set; }
    public int ConsumerId { get; set; }
}

(需确保已实现上述CustomDateTimeConverter类)

方案3:确保客户端字段正确赋值

首先取消注释consumer2.datelocal = date;这行代码,保证日期值被正确传入请求体,否则后端无法接收到该字段的数据。

内容的提问来源于stack exchange,提问作者rahul singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 12:51:00