Asp.net MVC Ajax调用未调用控制器方法 [英] Asp.net MVC Ajax call not calling controller method

查看:213
本文介绍了Asp.net MVC Ajax调用未调用控制器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个ASP.net MVC应用程序,因此,当用户单击链接时,它会执行ajax调用,将数据发送到控制器,然后将其他数据返回到视图.

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

这是控制器的位置:

08983ClassLibrary\EpostASP\Controllers\CustomerController.cs

这是我的Ajax电话:

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

当我在代码中放置断点时,我可以看到它击中了ajax调用,然后越过它永远不会到达控制器,也不会给出任何错误. 有什么想法吗?

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?

推荐答案

主要问题在这里-

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

您会看到,~是服务器端文字,换句话说,当您在ASP.net服务器端路径中使用它时,它会被当前服务器应用程序文件夹位置替换.这是传统的ASP.Net方法.该行有2个错误-

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. 此网址将永远无法使用.因为它在JS中的字符串中,因此ASP.net不知道它必须用服务器路径替换它.现在出现第二个错误,即使ASP.net可以检测到并转换它,它仍然无法工作.由于我在2点描述的观点-

  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 -

由于您正在使用ASP.net MVC,因此这不是一个好习惯.更传统的MVC方法是创建路由并使用这些路由.因为在ASP.net中,您可以选择直接链接到页面(.aspx,.ascx).但是,MVC控制器操作不能像这样链接.因此,您必须在路由配置中创建路由(选中Global.asax),然后在此处使用该路由作为url.默认情况下,MVC应用程序将支持以下格式-

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

示例-

'localhost/Home/Index`

请注意,我没有写HomeController,因为默认情况下,控制器应该忽略尾随字符串Controller.

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

更新: maproute(按comment的要求)将适用于这些路线中的任何一条.但也可以使用不同的路由配置.路由配置非常灵活,只需以适合您的方式设置路由即可. -

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

这篇关于Asp.net MVC Ajax调用未调用控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆