0

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.

Diego Perez
  • 2,188
  • 2
  • 30
  • 58
  • 1
    that is impossible, create an action in your controller which calls `GenerateAzureUrl()` then call your controller/action from ajax. – Okan Kocyigit May 10 '19 at 13:41

2 Answers2

1

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) {
    }
});
rtaggart
  • 51
  • 4
  • Thank you very much @rtaggart, the same, your help was very useful and I'll mark it as correct because of the posted code. – Diego Perez May 13 '19 at 07:09
0

You cannot use like that, as you already has answer with you "Controller". AJAX from Web browser take routing help to call the methods.

Check other reference: Ajax method call

Thanks