【问题标题】:Right path to ASP.NET MVC4 Controller's ActionMethod to use for ajax用于 ajax 的 ASP.NET MVC 4 控制器操作方法的正确路径
【发布时间】:2016-07-18 06:36:34
【问题描述】:

我有以下 MVC4 应用程序结构:


我正在尝试从 Index.cshtml 对位于我的 HomeController.cs 中的 SomeActionMethod() 进行 ajax 调用

Index.cshtml 看起来像:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="Scripts/jquery-2.2.2.min.js"></script>
</head>
<body>
    <script>
    $.ajax({
        url: '@Url.Action("SomeActionMethod", "HomeController")',
        type: "POST",
        cache: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data);
        },
        error: function () {
            alert("fail");
        }
    });
    </script>
</body>
</html>

HomeController.cs 看起来像:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SapRepLanciatoreCAS.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        //trying to invoke from ajax
        [HttpPost]
        public ActionResult SomeActionMethod()
        {
            return Json(new { foo = "bar", baz = "Blech" });
        }
    }
}

当我启动我的应用程序时,我收到了这个错误:

路径或控制器有什么问题?

【问题讨论】:

    标签: c# asp.net ajax asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    MVC 将controller 名称的第一部分考虑在内,即忽略Controller 关键字(请参阅您的观点,它被称为Home)。所以你的网址应该是 - 将HomeController更改为Home

    url: '@Url.Action("SomeActionMethod", "Home")',
    

    【讨论】:

    • 我知道这很令人沮丧,尝试使用 Resharper 等工具,它会显示诸如此类的视图错误 ;)
    • ASP.NET MVC 中的这种模式让我有些困惑。
    【解决方案2】:
    url:'@Url("Method Name","Controller Name")' 
    

    希望这会对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-03-30
      • 2010-12-15
      • 1970-01-01
      • 2019-01-26
      • 2014-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多