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

but5z9lq  于 12个月前  发布在  Java
关注(0)|答案(1)|浏览(109)

我有一个控制器方法:

[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脚本中调用这个方法。我使用apache没有问题:

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而不是apache时,它不起作用。

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。

vyswwuz2

vyswwuz21#

我复制了你的相关代码,你可以在头中添加相关配置,例如:'Accept': 'application/json',headers - Specify 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发送数据时:
x1c 0d1xx 1c 1d 1x如果要以以下代码的形式传递数据:

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来接收它(这样你需要解析数据并将其格式化):

相关问题