我有一个控制器方法:
[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。
1条答案
按热度按时间vyswwuz21#
我复制了你的相关代码,你可以在头中添加相关配置,例如:
'Accept': 'application/json'
,headers - Specify Accept和Content-Type HTTP请求头。这两个头都设置为application/json,分别指定接收和发送的媒体类型。并且你可以在控制器中添加frombody属性,以接受来自请求体的数据。如果你想传递一个额外的id参数,你想使用:用途:
字符串
此表单接收到数据后,可以插入JavaScript变量Id的值。可以参考这个例子:
我的收获:
型
我的控制器:
型
当我通过fetch发送数据时:
x1c 0d1xx 1c 1d 1x如果要以以下代码的形式传递数据:
型
您可以参考这两种方法:
首先:
您可以创建一个新模型来定义相应的模型,然后使用
[FromBody]
属性将相关数据绑定到模型:新型号:
型
获取:
型
接收此模型:
第二个
使用
Jsondocument
来接收它(这样你需要解析数据并将其格式化):