Asp.net MVC ActionResult如何检测可选参数?

时间:2013-12-01 19:28:21

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

我想检测一个可选参数是否已从url

传递给我的案例字符串Professional中的ActionResult

site.com/Account/Register/Professional 应该设置模型IsProfessional = true

site.com/Account/Register/ 应该设置模型IsProfessional = false

使用以下代码字符串professional始终为null。

知道怎么解决吗?

   public ActionResult Register(string professional)
    {
        // DETECT HERE
        RegisterViewModel model = new RegisterViewModel();
        if (!string.IsNullOrWhiteSpace(professional) && professional.ToLower() == "professional")
        {
            model.IsProfessional = true;
        }
        return View();
    }



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

1 个答案:

答案 0 :(得分:2)

使用与MapRoute匹配的ID,而不是使用专业版。请尝试以下代码:

    public ActionResult Register(string id)
    {
        var model = new RegisterViewModel();
        if (!string.IsNullOrWhiteSpace(id) && id.ToLower() == "professional")
        {
            model.IsProfessional = true;
        }
        else
        {
            model.IsProfessional = false;
        }
        return View();
    }