【问题标题】:Routing behaviour with Jquery AJAX call, MVC使用 Jquery AJAX 调用、MVC 的路由行为
【发布时间】:2019-01-10 03:36:23
【问题描述】:

您好,我正在尝试解决如何进行 Jquery ajax 调用,但我不明白为什么我的路由没有按预期进行。

我的路由很标准

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

    }

这是我正在调用的控制器操作

    [HttpPost]
    public ActionResult TestPost(string teststring)
    {
        return Json("test");
    }

这是我的 Ajax 调用

    $(document).ready(function (){
    /* attach a submit handler to the form */
    $("#input").submit(function (event) {

        /* stop form from submitting normally */
        event.preventDefault();

        alert('in the ajax');
        teststring = 'tested string';

        // check form is valid
        if ($("#input").valid()) {
            //ajax call!
            $.ajax({
                url : "Home/TestPost",
                type: "POST",
                cache: false
            });
        }
        else { return false }

但是当我运行这个调用时,它似乎没有在输出窗口中路由到 Home/Testpost,它似乎正在前往 Home/Home/TestPost

    {"ver":2,"id":"ZjW6WxGC8Yg=","name":"POST Home/Home","duration":"00:00:00.0290000","success":false,"responseCode":"404","url":"http://localhost:20064/Home/Home/TestPost"

所以我决定从我的 url 中删除 Home,所以我没有得到 2 个,但我仍然得到奇怪的结果,Testpost/Index

    ver":2,"id":"cfAk091y/V8=","name":"POST TestPost/Index","duration":"00:00:00.0100000","success":false,"responseCode":"404","url":"http://localhost:20064/TestPost","properties":{"DeveloperMode":"true"}}}}

对这种行为感到困惑

【问题讨论】:

  • 始终使用@Url.Action(...) 生成您的网址(这将正确生成/Home/TestPost

标签: jquery ajax asp.net-mvc routing


【解决方案1】:

您在 AJAX 调用中缺少一个斜线。你必须在前面有斜线

首页

url 值中的控制器。

所以你的代码必须是这样的:

   $.ajax({
                url : "/Home/TestPost",
                type: "POST",
                cache: false
            });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-12
    • 2014-08-16
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多