【问题标题】:receiving 404 error when trying to post to controller尝试发布到控制器时收到 404 错误
【发布时间】:2020-02-09 17:27:37
【问题描述】:

我正在尝试调用我的控制器方法并传递 2 个参数,但控制器操作从未被命中并返回 404 错误。

查看其他类似问题后,我尝试重新格式化 actionlink 并尝试使用 @html.action,确保它是 HttpGet 而不是 HttpPost,并且显然使 action 方法实际上存在于控制器中。

动作结果:

     @Html.ActionLink(
                   linkText: item.FileName,
                   actionName: "GetStatement",
                   controllerName: "Statements",
                   routeValues: new { id = item.Id, entityCode = 
    item.EntityCode },
                   htmlAttributes: null)

控制器方法

public class StatementsController : Controller
    {
        [HttpGet]
        public ActionResult GetStatement(int id, int entityCode)
        {
           //go to repository and get statement
        }
    }

我也不确定相应的 URL 格式是否正确: Statments/GetStatement/1234?entityCode=111

【问题讨论】:

    标签: asp.net-mvc actionlink


    【解决方案1】:

    请检查这个你需要更改一些小代码。

    在cshtml页面中

     @Html.ActionLink(
                       linkText: item.FileName,
                       actionName: "GetStatement",
                       controllerName: "Statements",
                       routeValues: new { itemid = item.Id, entityCode = 
        item.EntityCode },
                       htmlAttributes: null)
    

    控制器代码

    public class StatementsController : Controller
        {
            [HttpGet]
            public ActionResult GetStatement(int itemid, int entityCode)
            {
               //go to repository and get statement
            }
        }
    

    注意:当您在控制器操作中传递“Id”时,会在下面的示例中自动路由转换

    public ActionResult HandleException(int id)
            {
                // id mentioned in **RouteConfig** file that's way URL automatic mapped
            }
    

    查看 RouteConfig 文件

    public class RouteConfig
        {
            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 }
                );
            }            
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      • 2014-10-14
      • 2018-10-17
      • 2021-08-05
      相关资源
      最近更新 更多