【问题标题】:'The resource cannot be found' using HttpPost in MVC在 MVC 中使用 HttpPost '找不到资源'
【发布时间】:2013-05-27 16:02:51
【问题描述】:

我发现我的问题是一个常见错误,并且已经尝试了很多解决此问题的方法,但它仍然不适合我。所以,从头开始,我在一个 MVC 项目中有一个部分表单,它使用 Html.BeginForm 帮助器:

<%using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new{@class = "form-class"}))

"MyAction" 和 "MyController" 不是实际名称,但它们在带下划线的名称确认时被解析。我在控制器中的操作是:

[HttpPost]
    public ActionResult MyAction(int id, FormCollection form)
    {
     EditedData dt = new EditedData();
      // does some db submits and returns edited data

        return View(dt);
    }

所以,看起来常见的问题是,使用 [HttpPost] 返回错误“找不到资源”。我已经用 [HttpPost] 进行了调试,注释掉了哪个命中 MyAction,所以它不是路由(?)。我的global.asax 未更改:

public class MvcApplication : System.Web.HttpApplication
{

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

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

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

    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
}

正如我所说,我在其他帖子中尝试了其他答案,这似乎对海报有用,但我仍然遇到问题。我错过了什么?

附:在查看源代码中,我看到表单标签显示:

<form method="post" action="690" id="form1">

action 何时应该指向 MyAction。如何将 Html.BeginForm 设置为指向“MyAction”?

【问题讨论】:

    标签: c# html asp.net-mvc


    【解决方案1】:

    问题是动作的id 参数是一个int(值类型),它不能作为空引用传递。因此,您需要在 BeginForm 调用中(在视图中)将其显式设置为 0 或使其可为空。

    基本上,路由引擎无法根据您提供的数据(操作名称和控制器名称)+ 路由映射来解析您的操作和控制器。

    示例(如果您决定将参数保留为int):

    <%using (Html.BeginForm("MyAction", "MyController", new { id = 0 }, FormMethod.Post, new { @class = "form-class" }))
    

    然后,此重载将匹配您在控制器中指定的签名。编辑时,只需将 0 替换为任何匹配的模型属性即可;例如:

    <% using (Html.BeginForm("MyAction", "MyController", new { id=Model.ID }, FormMethod.Post, new{ @class = "form-class"})) %>
    

    【讨论】:

    • 是的,这就是问题所在。但我希望动作读取 action="MyAction" 而不是 action="690"。我看不出将它设置为 0 或 null 将如何解决我的问题。可以举个例子吗?
    • @marceln 我正要添加一个与您上次编辑基本相同的答案,所以我添加了一点与您的不同的答案。如果您不批准,则回滚编辑。
    • @user2284341:上面有两个示例。随便挑吧:)。它会起作用的。
    猜你喜欢
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多