【问题标题】:Catch object from ajax - asp.net core 2.1从 ajax 捕获对象 - asp.net core 2.1
【发布时间】:2021-01-11 18:12:43
【问题描述】:

我正在尝试将整个对象从 javascript 发送到 asp.net 核心控制器。

这是我正在学习的 C# 类:

public class AREvent
{
    public int ID { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
}

我像这样从 ajax 传递它:

function Upp() {
    var ev = {};

    ev.ID = 1;
    ev.Title = "asd";
    ev.Text = "Some text";

    var fd = new FormData();
    fd.append("e", ev);
    fd.append("aaa", "Some text");

    alert(ev.ID); // alerts 1

    $.ajax({
        type: "POST",
        url: "/Events/Add1",
        cache: false,
        contentType: false,
        processData: false,
        data: fd,
        success: function () {
        }
    });
}

这里是控制器:

[HttpPost]
[Route("/Events/Add1")]
public async Task<IActionResult> Add1(AR.AREvent e, string aaa)
{
    /// aaa is passed as "some text"
    /// e is passed as null or as empty object
    object a = e;
    return Json("1");
}

【问题讨论】:

    标签: javascript asp.net ajax asp.net-core


    【解决方案1】:

    您不需要传递 FormData。 你必须像这样传递对象:

    $.ajax({
                url: "/Events/Add1",
                type: 'POST',
                dataType: 'json',
                data: JSON.stringify(ev),
                contentType:  "application/json",
                success: function (result, text, xhr) {
    
                },
                error: function (request, status, error) {
                }
            });
    

    在控制器中:

    [HttpPost]
    [Route("/Events/Add1")]
    public async Task<IActionResult> Add1([FromBody] AREvent e)
    {
        AREvent a = e;
        return Json("1");
    }
    

    【讨论】:

      【解决方案2】:

      据我所知,如果你想将表单数据传递给控制器​​,没有必要新建一个名为ev的新js模型。直接在js中的表单数据模型中添加属性值,asp.net核心模型绑定会自动绑定该值。模型绑定会根据表单数据名而不是对象来映射属性。

      更多细节,您可以参考以下代码:

      function Upp() {
        
      
          var fd = new FormData();
          fd.append("ID", 1);
          fd.append("Title", "asd");
          fd.append("Text", "Some text");
          fd.append("aaa", "Some text2");
      
          $.ajax({
              type: "POST",
              url: "/Events/Add1",
              cache: false,
              contentType: false,
              processData: false,
              data: fd,
              success: function () {
              }
          });
      }
      

      结果:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-12
        • 2019-12-31
        • 2020-09-10
        • 1970-01-01
        相关资源
        最近更新 更多