首页 > 解决方案 > 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.

标签: c#ajaxasp.net-mvcmodel-view-controllerasp.net-ajax

解决方案


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) {
    }
});

推荐阅读