[英]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. 我正在一个MVC C#Web上工作,该Web具有一个“共享”项目,该项目具有一个名为ImageUrlHelper的Helper类,该类具有一个称为GenerateAzureUrl的方法,该方法返回一个字符串,并且我需要通过ajax调用来调用此方法。
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. 但这是行不通的,我猜您只能从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. 我收到的是404 Not Found。
Thanks. 谢谢。
As mentioned in the comments, 如评论中所述,
Create an action in a controller class that calls the GenerateAzureUrl() method. 在控制器类中创建一个调用GenerateAzureUrl()方法的操作。
[HttpPost]
[Route("get/azure/url/from/api/{path}")]
public string GetAzureUrlFromAPI(string path)
{
return GenerateAzureUrl(path);
}
In AJAX call: 在AJAX通话中:
$.ajax({
type: 'POST',
url: '../../../get/azure/url/from/api/' + path,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
}
});
You cannot use like that, as you already has answer with you "Controller". 您不能那样使用,因为您已经有了“控制器”的答案。 AJAX from Web browser take routing help to call the methods.
Web浏览器的AJAX获得路由帮助来调用方法。
Check other reference: Ajax method call 检查其他参考: Ajax方法调用
Thanks 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.