【问题标题】:How can I convert MVC Route to parameter of type Boolean?如何将 MVC Route 转换为布尔类型的参数?
【发布时间】:2016-03-04 15:04:47
【问题描述】:

将路线段更改为布尔值

我的控制器中有一个简单的操作方法,并且想在 url 中传递字符串“Company”时将布尔值传递给我的操作。

public ActionResult DoSomething(Boolean ? isCompany) {  }

我想这样称呼它。

http://mysite/Feature/Configure/Company

所以基本上,当“公司”在 url 中时,然后将 isCompany 作为 true 布尔值传递。

这可能吗?

根据下面的答案,我认为我应该使用以下映射。

routes.MapRoute(
    name: "FeatureConfigure",
    url: "Feature/Configure/{company}",
    defaults: new { controller = "Feature", action="Configure", 
       company = UrlParameter.Optional }
    );

public ActionResult Configure(String company) {
   var isCompany = company == "Company";
   // maybe use a switch if there are multiple values company can be
   // and probably rename the variable to something more generic.
}

【问题讨论】:

  • 您还有其他可能匹配该路径的情况吗?即你可能有/feature/configure/user,甚至只是/feature/configure/
  • 有两种可能?我更改了代码以反映对需要具有多个值的任何人的公司变量的更多关注。

标签: asp.net-mvc model-view-controller controller routing


【解决方案1】:

不是直接的,你必须像这样处理它:

public ActionResult DoSometing(string foo)
{
    var isCompany = foo == "Company";
}

【讨论】:

    【解决方案2】:

    真正回到您想要实现的目标。 对这样的输入进行检查表明您将计划在您的逻辑中有一个分支,并可能显示不同的内容/视图。

    更简单的选择是让 MVC 处理它并保持代码更简洁。

    选项 1:

    将路由的 {company} 部分更改为 {action} 并在操作级别分叉您的逻辑。

    routes.MapRoute(
    name: "FeatureConfigure",
    url: "Feature/Configure/{action}",
    defaults: new { controller = "Feature", action="Index" }
    );
    
    public ActionResult Company() {
        // Do company stuff
    }
    
    public ActionResult Branch() {
        // Do branch stuff
    }
    

    选项 2:

    与上述相同,但使用路由属性(假设您使用的是 MVC5)。 为此,请从配置中删除 FeatureConfigure 路由。

    然后在控制器和操作中包含以下内容:

    [RoutePrefix("features/configure")]
    public class FeatureController : Controller
    {
        ....
        [Route("{type:regex(company)}")]
        public ActionResult Company()
        {
            // do company stuff
        }
    
        [Route("{type:regex(branch)}")]
        public ActionResult Branch()
        {
            // do branch stuff
        }
    
        ...
    }
    

    注意:在任何一种情况下,将 FeatureController 重命名为 ConfigureContoller 可能更有意义,但这取决于您

    【讨论】:

      猜你喜欢
      • 2012-03-12
      • 1970-01-01
      • 1970-01-01
      • 2014-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      相关资源
      最近更新 更多