c# - MVC C# call non controller method (helper) from ajax. Possible or not?
问题描述
I'm working on an MVC C# web that has a "shared" project which has a Helper class called ImageUrlHelper that has a method called GenerateAzureUrl which returns a string, and I need to call this method through an ajax call.
I've tried:
$.ajax({
type: 'POST',
url: '/Helpers/ImageUrlHelper/GenerateAzureUrl',
data: '{ "path": "' + path + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
}
});
But it's not working, and I'm guessing you can only call a controller method from Ajax. Am I right? Or maybe it should work and I'm doing something wrong in my call.
BTW, this is my Helper method:
public static string GenerateAzureUrl(string path)
{
var pathPartsFromI = Regex.Split(path, "/i/");
if (pathPartsFromI.Length != 2) return path;
var rightPathParts = Regex.Split(pathPartsFromI[1], "/");
if (rightPathParts.Length < 2) return path;
var id = rightPathParts[0];
var size = (rightPathParts.Length == 2 ? "ori" : rightPathParts[1]);
var slug = rightPathParts[rightPathParts.Length - 1];
var extension = slug.Split('.')[1].Split('%')[0];
string azureUrl = _urlAzureImageDomain + "/images/" + size.ToLower() + "/" + id + "." + extension;
bool imgExists = ImageExists(id, size.ToLower(), extension);
if (!imgExists)
{
if (size.ToLower() != "ori") imgExists = ImageExists(id, "ori", extension);
if (!imgExists) return "/Content/images/image_not_found.jpg";
azureUrl = _urlAzureImageDomain + "/images/ori/" + id + "." + extension;
}
return azureUrl;
}
What I'm receiving is a 404 Not Found.
Thanks.
解决方案
As mentioned in the comments,
Create an action in a controller class that calls the GenerateAzureUrl() method.
[HttpPost]
[Route("get/azure/url/from/api/{path}")]
public string GetAzureUrlFromAPI(string path)
{
return GenerateAzureUrl(path);
}
In AJAX call:
$.ajax({
type: 'POST',
url: '../../../get/azure/url/from/api/' + path,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
}
});
推荐阅读
- flutter - 为什么 DataTable 在 Flutter 中不显示 JSON
- php - 允许显示一些 OutOfStock 产品
- javascript - 为什么函数返回的数据没有在反应中呈现?
- swift - 您好需要帮助以将数字存储在连接到步进器的标签中
- javascript - Html-Select-Tag-如何在不使用 eval() 的情况下将字符串值转换为 javascript?
- c - 如何从文本文件中仅读取具有未知数量整数的行到数组中(在 C 中)
- javascript - 根据数组中的现有值动态更改下拉选择默认值
- javascript - 带有动画下划线的中心链接
- c# - MaxDegreeOfParallelism 不限制并行任务的数量
- arrays - 将大型 std::vector 放入 Swift 的最有效方法?