【问题标题】:Redirect to a different MVC controller when supplying an empty URL parameter?提供空 URL 参数时重定向到不同的 MVC 控制器?
【发布时间】:2015-06-09 20:09:16
【问题描述】:

问题背景:

我有一个 URL,其中包含一个名为 pageNo 的参数,该参数通过一个名为 FutureEvents 的方法发送到名为 Events 的控制器。这与分页一起使用来确定需要显示的视图的页码。这是网址:

http://localhost:xxxxx/Events/FutureEvents?pageNo=1

问题:

如果用户手动键入 URL 并且没有在 URL 中提供页码参数,例如:

http://localhost:51025/Events/FutureEvents

然后显示 ASP 错误并显示以下消息:

参数字典包含方法的不可空类型“System.Int32”的参数“pageNo”的空条目 'System.Web.Mvc.ActionResult FutureEvents(Int32)'

这是有道理的,因为参数为空。当用户尝试使用空的pageNo 参数调用FutureEvents 控制器和Events 方法时,我想要做的是将用户重定向到另一个控制器(在本例中是我的Home 控制器和Index 方法) .

这是我目前的路线:

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

Home 控制器及其 Index 方法 - 这是我想要重定向到的。

 public ActionResult Index()
 {
    return View();
 }

带有Events 方法的FutureEvents 控制器:

 [HttpGet]
 public ActionResult FutureEvents(int pageNo)
 {
     //code
 }

【问题讨论】:

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


    【解决方案1】:

    如果你在函数中传递参数,我们需要把 then 或设置一个初始值。

    int pageNo = 0 还是 int?页号

       [HttpGet]
         public ActionResult FutureEvents(int pageNo = 0)
         {
             //code
         }
    

    其他所有不带参数的函数都正常打开。

    【讨论】:

      【解决方案2】:

      你必须定义两条路由,一条带参数(非可选),一条不带参数。

      routes.MapRoute( // because id is required, route will be skipped
              name: "Default",
              url: "{controller}/{action}/{id}",
              defaults: new { controller = "Events", action = "FutureEvents"}
          );
      
      routes.MapRoute( // catch all routes that doesn't match the others.
              name: "CatchAll",
              url: "{*everything}",
              defaults: new { controller = "Home", action = "Index" }
          );
      

      你可以看到more informations的这个答案。

      【讨论】:

        【解决方案3】:

        或者如果你想使用会话来传递页码 这样他们就不用担心用户编辑页码了

        会话[“页码”]=值;

        //重定向到一个动作

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-10-26
          • 2015-09-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多