ASP.NET Core 2.2 Razor Pages - AJAX 调用页面模型不返回数据
ASP.NET Core 2.2 Razor Pages - AJAX Call to page model not returning data
我是 AJAX 的新手,甚至无法掌握正确运行的基础知识。
我 运行 从 razor 页面 javascript 部分的函数内调用 AJAX,但我无法获得要 returned 所需的字符串值。
我在警告框中得到的结果只是将 razor 页面的 HTML 布局显示为消息,而不是我想要 return 的实际字符串。我花了几个小时试图将 X-CSRF-TOKEN 合并到 header 中,但这没有任何区别。我不确定这里是否需要防伪令牌,因此问题出在这一步之前。
剃刀页面:
$.ajax({
type: "GET",
url: "/Maps?handler=CanvasBackgroundImage",
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
页面模型:
public JsonResult OnGetCanvasBackgroundImage()
{
var result = "test message";
return new JsonResult(result);
}
下面是我现在可以使用的代码。感谢大家的参与。
Razor 页面(脚本部分):
function getMapBackgroundImagePath() {
// Get the image path from AJAX Query to page model server side.
$.ajax({
type: "GET",
url: "/Maps/Create?handler=MapBackgroundImagePath",
contentType: "application/json",
data: { imageId: imageId, }, // Pass the imageId as a string variable to the server side method.
dataType: "json",
success: function (response) {
copyText = response;
// Run the function below with the value returned from the server.
renderCanvasWithBackgroundImage();
},
});
}
页面模型:
public JsonResult OnGetMapBackgroundImagePath(string imageId)
{
// Get the image full path where the id = imageId string
int id = Convert.ToInt32(imageId);
var imagePath = _context.Image.Where(a => a.ID == id)
.Select(i => i.ImageSchedule);
// return the full image path back to js query in razor page script.
return new JsonResult(imagePath);
}
我是 AJAX 的新手,甚至无法掌握正确运行的基础知识。
我 运行 从 razor 页面 javascript 部分的函数内调用 AJAX,但我无法获得要 returned 所需的字符串值。
我在警告框中得到的结果只是将 razor 页面的 HTML 布局显示为消息,而不是我想要 return 的实际字符串。我花了几个小时试图将 X-CSRF-TOKEN 合并到 header 中,但这没有任何区别。我不确定这里是否需要防伪令牌,因此问题出在这一步之前。
剃刀页面:
$.ajax({
type: "GET",
url: "/Maps?handler=CanvasBackgroundImage",
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
页面模型:
public JsonResult OnGetCanvasBackgroundImage()
{
var result = "test message";
return new JsonResult(result);
}
下面是我现在可以使用的代码。感谢大家的参与。
Razor 页面(脚本部分):
function getMapBackgroundImagePath() {
// Get the image path from AJAX Query to page model server side.
$.ajax({
type: "GET",
url: "/Maps/Create?handler=MapBackgroundImagePath",
contentType: "application/json",
data: { imageId: imageId, }, // Pass the imageId as a string variable to the server side method.
dataType: "json",
success: function (response) {
copyText = response;
// Run the function below with the value returned from the server.
renderCanvasWithBackgroundImage();
},
});
}
页面模型:
public JsonResult OnGetMapBackgroundImagePath(string imageId)
{
// Get the image full path where the id = imageId string
int id = Convert.ToInt32(imageId);
var imagePath = _context.Image.Where(a => a.ID == id)
.Select(i => i.ImageSchedule);
// return the full image path back to js query in razor page script.
return new JsonResult(imagePath);
}