【问题标题】:How to convert a $('#form').serializeArray() to c# class object with Ajax?如何使用 Ajax 将 $('#form').serializeArray() 转换为 c# 类对象?
【发布时间】:2021-04-09 11:53:24
【问题描述】:

我有一个名为 Location 的模型类:

  public class Location
  {
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public int Number { get; set; }
    public int? Floor { get; set; }
    public string ImgURL { get; set; }
    public string Type { get; set; }
    public double Longitude { get; set; }
    public double Latitude { get; set; }
  }

在我的 .cshtml.cs Razor 页面中,我有一个名为 MapLocationModel 的 PageModel 和一个名为 CurrentLocation 的属性:

    [BindProperty]
    public Location CurrentLocation { get; set; }

我在模态表单中使用此属性:

<form id="locationForm" method="post">
               
     <!--CurrentLocation.Name-->
     <div class="form-group col-md-9">
         <label asp-for="CurrentLocation.Name" class="control-label"></label>
         <input asp-for="CurrentLocation.Name" class="form-control" />
         <span asp-validation-for="CurrentLocation.Name" class="text-danger"></span>
     </div>

     // Here all other properties
                  
</form>
        
  <div class="modal-footer">
      <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      <input type="button" id="buttonSubmit" value="Submit" class="btn btn-primary" />
  </div>

现在我想要实现的是将 CurrentLocation 传递给 ajax 帖子。 到目前为止,我已经编写了我的 ajax 函数:

var button = $("#buttonSubmit");
button.on('click', function () {
    var location = $('#locationForm').serializeArray();
    $.ajax({
        type: "POST",
        url: "/Map/MapLocation?handler=AsyncMyLocationAjax",
        headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
        data: { currentLocation: location },
        success: function (response) {
            alert(response);
        }
    });
});

但我的处理程序总是返回 null :

    public ActionResult OnPostAsyncMyLocationAjax(Location currentLocation)
    {
        Console.WriteLine(currentLocation);
        // currentLocation is always null
    }

我认为问题在于 RequestVerificationToken 是序列化的一部分:

我已经阅读了很多关于如何使用 ajax 传递数据的帖子,但我仍然不明白如何去做。

我做错了什么?如何将var location = $('#locationForm').serializeArray(); 转换为Location 对象?

【问题讨论】:

  • 这能回答你的问题吗? HTML form sent by Ajax and handle with PHP
  • 首先你的问题是你的 jquery fnc。您需要处理 $form.on('submit'.. 以使 serializeArray 这个发送表单具有正确的标题(多部分/表单),其次如果您仍想以 ajax 形式发送数据,您需要创建正确的 js 对象或使用 .map fnc 来你的 serializeArray 结果。检查我的评论。
  • @daremachine 我不认为我对 SerializeArray 有问题,这部分工作正常(你可以看到截图,我的数据在数组中)。我也知道如何通过传递单个属性然后 JSON.stringify() 来序列化为 Json。我只是想避免在我的函数中将我的类重新创建为 Json 对象。那么序列化表单有什么好处呢?另外我不懂 PHP,所以我不知道它的工作方式是否与 asp.net 相同。
  • 所有工作都一样,因为这就是 Web 应用程序的工作方式。但尝试添加 'FromForm' ... OnPostAsyncMyLocationAjax([FromForm] Location currentLocation)
  • 不,它不起作用,我也尝试过 [FromQuery],还将 SerializeArray 更改为 Serialize。但是这 4 种组合都不起作用。

标签: c# ajax asp.net-core razor-pages


【解决方案1】:

serializeArrayserialize 都会生成__RequestVerificationToken,您需要通过表单而不是通过json 传递数据。所以将data: { currentLocation: location } 更改为data: location,如下所示:

var button = $("#buttonSubmit");
button.on('click', function () {
    var location = $('#locationForm').serializeArray();
    console.log(location);
    $.ajax({
        type: "POST",
        url: "/Map/MapLocation?handler=AsyncMyLocationAjax",
        headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
        data: location,
        success: function (response) {
            alert(response);
        }
    });
});

结果:

【讨论】:

  • 非常感谢!这是工作。我觉得好傻,好像很简单。再次感谢您的宝贵时间。
猜你喜欢
  • 2014-04-26
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-10
  • 1970-01-01
相关资源
最近更新 更多