使用 fetch 将复杂对象从 javascript 传递到 MVC 控制器

问题描述 投票:0回答:1

我有一个控制器方法:

        [HttpPost]
    public async Task<IActionResult> GetTextFromPos(int id,Position position)
    {
        if (position==null || _context.Batches == null)
        {
            return NotFound();
        }

        var batchesModel = await _context.Batches
            .Include(b => b.Profile)
            .ThenInclude(b => b.Fields)
            .FirstOrDefaultAsync(m => m.Id == id);

        batchesModel.OcrData = await _ocrStorageService.LoadOcrDataFromFileSystem(batchesModel.Id);

        var foundText = "This is found text: "+batchesModel.GetTextFromPosition(position);

        return Json(foundText); 

    }

我需要从 JS 脚本调用这个方法。 我使用ajax没有任何问题:

async function getTextFromPos(id, left, top, right, bottom) {
    const reverseScaleFactor = 1 / scale_factor;
    // Reverse the scaling on the coordinates and round them to integers
    const reverseLeft = Math.round(left * reverseScaleFactor);
    const reverseTop = Math.round(top * reverseScaleFactor);
    const reverseRight = Math.round(right * reverseScaleFactor);
    const reverseBottom = Math.round(bottom * reverseScaleFactor);

    var payload = {
        id: id,
        position: { left: reverseLeft, top: reverseTop, right: reverseRight, bottom: reverseBottom }
    };
    $.ajax({
        url: '/Batches/GetTextFromPos',
        type: 'POST',
        data: payload,
        success: function (response) {
            // Handle the successful response here
            console.log('Response: ', response);
        },
        error: function (error) {
            // Handle any errors that occur during the request
            console.error('Error:', error);
        }
    });
    }

但是当我尝试使用 fetch 而不是 ajax 时,它不起作用

async function getTextFromPos(id, left, top, right, bottom) {
    const reverseScaleFactor = 1 / scale_factor;
    const reverseLeft = Math.round(left * reverseScaleFactor);
    const reverseTop = Math.round(top * reverseScaleFactor);
    const reverseRight = Math.round(right * reverseScaleFactor);
    const reverseBottom = Math.round(bottom * reverseScaleFactor);

    const payload = {
        id: id,
        left: reverseLeft,
        top: reverseTop,
        right: reverseRight,
        bottom: reverseBottom
    };

    try {
        const response = await fetch('/Batches/GetTextFromPos', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const responseData = await response.json();
        console.log('Response:', responseData);
        // Handle the successful response here
    } catch (error) {
        console.error('Error:', error);
        // Handle any errors that occur during the request
    }
}

我尝试更改内容类型,将 [FormBody] 添加到控制器功能的参数中 - 没有任何效果。 Id 始终为 0,位置值为 null。

javascript asp.net asp.net-mvc asp.net-core model-view-controller
1个回答
0
投票

我复制了你的相关代码,你可以在 headers 中添加相关配置,例如:

'Accept': 'application/json'
, headers — 指定 Accept 和 Content-Type HTTP 请求标头。两个标头都设置为 application/json 以分别指定接收和发送的媒体类型。 您可以在控制器中添加 frombody 属性来接受来自请求正文的数据。

如果你想传递额外的id参数,你想使用:

public async Task<IActionResult> GetTextFromPos( int Id ,[FromBody] Position position) 

这个表单接收到数据后,可以插入JavaScript变量Id的值。你可以参考这个例子:

我的取物:

document.addEventListener("DOMContentLoaded", function () {

    const scale_factor = 1;
    const Id = 10;
    async function getTextFromPos(left, top, right, bottom) {
        const reverseScaleFactor = 1 / scale_factor;
        const reverseLeft = Math.round(left * reverseScaleFactor);
        const reverseTop = Math.round(top * reverseScaleFactor);
        const reverseRight = Math.round(right * reverseScaleFactor);
        const reverseBottom = Math.round(bottom * reverseScaleFactor);

        var payload = {
            left: reverseLeft,
            top: reverseTop,
            right: reverseRight,
            bottom: reverseBottom
        }

        const response = await fetch(`/Fetch/GetTextFromPos/${Id}`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        })
            .then(response => response.json())
            .then(responseData => {
                console.log('Success:', responseData);
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }


    const myLeft = 10;
    const myTop = 20;
    const myRight = 30;
    const myBottom = 40;

    getTextFromPos(myLeft, myTop, myRight, myBottom);
});

我的控制器:

[HttpPost]
public async Task<IActionResult> GetTextFromPos( int Id ,[FromBody] Position position)
{
var foundText = "This is found text: ";

return Json(foundText);
}

当我通过 fetch 发送数据时:

如果想通过以下代码的形式传递数据:

var payload = {
     id: Id, 
     position: { left: reverseLeft, top: reverseTop, right: reverseRight, bottom: reverseBottom }
};

您可以参考这两种方法:

第一:

可以新建一个模型来定义对应的模型,然后使用

[FromBody]
属性将相关数据绑定到模型上:

新型号:

public class PayloadModel
  {
      public int Id { get; set; }
      public Position Position { get; set; }
  }

获取:

document.addEventListener("DOMContentLoaded", function () {

     const scale_factor = 1;
     const Id = 10;

     async function getTextFromPos(left, top, right, bottom) {
         const reverseScaleFactor = 1 / scale_factor;
         const reverseLeft = Math.round(left * reverseScaleFactor);
         const reverseTop = Math.round(top * reverseScaleFactor);
         const reverseRight = Math.round(right * reverseScaleFactor);
         const reverseBottom = Math.round(bottom * reverseScaleFactor);

         var payload = {
             id: Id, 
             position: { left: reverseLeft, top: reverseTop, right: reverseRight, bottom: reverseBottom }
         };

         try {
             const response = await fetch('/Fetch/GetTextFromPos', {
                 method: 'POST',
                 headers: {
                     'Accept': 'application/json',
                     'Content-Type': 'application/json'
                 },
                 body: JSON.stringify(payload)
             });

             if (response.ok) {
                 const responseData = await response.json();
                 console.log('Success:', responseData);
             } else {
                 console.error('Error:', response.statusText);
             }
         } catch (error) {
             console.error('Error:', error);
         }
     }

     const myLeft = 10;
     const myTop = 20;
     const myRight = 30;
     const myBottom = 40;

     getTextFromPos(myLeft, myTop, myRight, myBottom);
});

收到此模型:

第二个

使用

Jsondocument
接收(这样需要解析数据并反序列化):

© www.soinside.com 2019 - 2024. All rights reserved.