【发布时间】: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