Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net MVC Ajax call not calling controller method

I am making an ASP.net MVC application And I would like it so when a user clicks on a link it performs an ajax call sending data to the controller and then returning other data back to the view.

This is the method I would like to call in my controller:

public JsonResult GetImage(string url)
        {
            Image image = Image.FromFile(url, true);

            byte[] byteImage = converter.ImageToBytes(image);

            return Json(new { byteImage }, JsonRequestBehavior.AllowGet);
        }

And here is the controllers location:

08983ClassLibrary\EpostASP\Controllers\CustomerController.cs

This is my Ajax Call:

$.ajax({
            url: "~/Controllers/CustomerController/GetImage/",
            type: 'POST',
            contentType: 'application/json',
            data: "url="+url,
            success: function (image) {
                document.getElementById("image").src = "data:image/png;base64," + image;
                showImage();
            }
        });

When i place my breakpoints in the code I can see it hitting the ajax call then stepping over it never reaches the controller and doesnt give any errors. Any ideas?

like image 683
brian4342 Avatar asked May 01 '14 03:05

brian4342


2 Answers

The main issue is here -

url: "~/Controllers/CustomerController/GetImage/",

You see, ~ is a server side literal, in other words, when you use this in a ASP.net server side path, it is replaced by the current server application folder location. This was the traditional ASP.Net way. This line has 2 errors -

  1. This url will never work. Because its inside a string in JS and thus ASP.net does not know that it has to replace it with server path. Now comes the second error, even if ASP.net could detect and convert it, it will still not work. Because of the point I described at 2 -

  2. Since you are using ASP.net MVC, it's not a good practice. The more conventional MVC way is to create routes and use those routes. Because in ASP.net you have the option to link to a page (.aspx, .ascx) directly. But MVC controller actions cannot be linked like that. So you have to create routes in your route config (check Global.asax) and then use that route as the url in here. BY default MVC apps will support the following format -

    <host>/{controller}/action

    example -

    'localhost/Home/Index`
    

Notice that I didn't write HomeController, because by default controllers are supposed to ignore the trailing string Controller.

I hope this helped and just incase you are looking for a solution for your current situation try this (I haven't tested but it should be like this) -

 $.ajax({
        url: "Customer/GetImage",
        type: 'POST',
        contentType: 'application/json',
        data: "url="+url,
        success: function (image) {
            document.getElementById("image").src = "data:image/png;base64," + image;
            showImage();
        }
    });

but to be on the safe side, make sure you use -

[HttpPost]
public JsonResult GetImage(string url)
{
}

UPDATE: the maproute (as requested in comment ) will work with any of these routes. But can also work with different routes config. Route config is very very flexible, it is just a matter to setup the routes the way it works for you. -

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(
            "...",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

        routes.MapRoute(
            "...",                                              // Route name
            "{controller}/{action}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

        routes.MapRoute(
            "...",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Customer", action = "GetImage", id = "" }  // Parameter defaults
        );
        routes.MapRoute(
            "...",                                              // Route name
            "Customer/GetImage/{id}",                           // URL with parameters
            new { controller = "Customer", action = "GetImage", id = "" }  // Parameter defaults
        );
        ..... //all of these mentioned route will land on the same url 
    }

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }
like image 135
brainless coder Avatar answered Sep 24 '22 14:09

brainless coder


Your ajax script says it is looking for a POST action method.

$.ajax({type: 'POST',

Have you decorated the action method with POST?

[HttpPost]
public JsonResult GetImage(string url)
{
}

Also, adjust your ajax data parameter

$.ajax({
    data: {
        "url": url 
        },
like image 45
Yorro Avatar answered Sep 22 '22 14:09

Yorro