【问题标题】:check second parameter in asp.net检查asp.net中的第二个参数
【发布时间】:2018-11-14 20:16:20
【问题描述】:

我是 c# mvc 的新手,我正在尝试创建一个具有多个参数的路由,如下所示:

控制器/动作/parameterOne/parameterTwo

但在某些情况下,我将只使用其中一个,因此路线将如下所示:

controller/action/parameterOne

这是我的 RouteConfig.cs

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 }
        );

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

现在在我的控制器的操作中,我需要检查是否只有一个或两个参数,以便我可以为每个条件返回不同的视图,这里是控制器:

[HttpGet]
    public ActionResult someAction(string category, string id)
    {
        if (String.IsNullOrWhiteSpace(id))
        {
                return View("viewOne");
        }
        else
        {
            return View("ViewTwo");
        }
    }

问题是 if 语句没有完全工作?因为如果条件是这样的:String.IsNullOrWhiteSpace(id)

如果我写 controller/action/parameterOne 这将返回 ViewOne

但如果我写 controller/action/parameterOne/parameterTwo 也会返回 ViewOne

但是现在如果反转条件并且我写 !String.IsNullOrWhiteSpace(id) 两个 url 都返回 ViewTwo。

那么有人知道为什么会这样吗?

【问题讨论】:

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


    【解决方案1】:

    您是否反对只使用默认路由?想到的唯一缺点是,如果您真的希望您的 url 以某种方式显示,在这种情况下,您可能需要在尝试时定义多个路由。但是,以下内容应仅适用于默认路由:

    //note controller actions will default to HttpGet if no data annotation is explicitly supplied. Also, action names generally begin uppercase by convention
    public ActionResult SomeAction(string category, string id = null)
    {
        if (String.IsNullOrWhiteSpace(id))
        {
            return View("viewOne");
        }
        else
        {
            return View("ViewTwo");
        }
    }
    

    您提到的各种请求如下所示:

    www.myhost.com/controller/someaction?category=parameterOne&id=parameterTwo

    www.myhost.com/controller/someaction?category=parameterOne

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-23
      • 2021-11-23
      • 2012-12-09
      • 2021-11-20
      • 2016-03-11
      • 2018-08-31
      • 2018-03-22
      • 1970-01-01
      相关资源
      最近更新 更多