2个可选的整数参数

时间:2015-06-03 20:24:41

标签: c# asp.net-mvc

我的用户控制器操作如下:

[HttpGet]
public ActionResult Choose(int? userId, int? locationId)
{

}

网址如下:

/user/choose

/users/user/choose/{userId}/{locationId}

我试图将此添加到我的区域路线:

context.MapRoute(
    "User_Choose",
    "Users/{controller}/{action}/{userId}/{locationId}",
        new { Controller = "Reward", action = "Choose", userId = UrlParameter.Optional }
);

现在,如果我转到以下网址:

/users/user/choose/123/456

我看到userId参数有一个值,但locationId始终为null。

问题是什么?

1 个答案:

答案 0 :(得分:1)

修复可能在这里:

context.MapRoute(
    "User_Choose",
    "Users/{controller}/{action}/{userId}/{locationId}",
        new { controller = "Reward", action = "Choose", userId = UrlParameter.Optional, locationId = UrlParameter.Optional}
);

您必须指定括号对匿名对象的含义,即设置其默认值。

编辑:实际上您的代码没有问题。 我的控制器:

namespace WebApplication3.Areas.Users.Controllers
{
    public class UserController : Controller
    {
        // GET: Users/User
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult Choose(int? userId, int? locationId)
        {
            return View();
        }
    }
}

UsersAreaRegistration.cs:

namespace WebApplication3.Areas.Users
{
    public class UsersAreaRegistration : AreaRegistration 
    {
        public override string AreaName 
        {
            get 
            {
                return "Users";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context) 
        {
            context.MapRoute(
                "User_Choose",
                "Users/{controller}/{action}/{userId}/{locationId}",
                    new { controller = "Reward", action = "Choose", userId = UrlParameter.Optional }
            );
        }
    }
}

的Global.asax:

namespace WebApplication3
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

我总是使用您在Chose()方法中提供的网址获取这两个值。实际问题可能在于您的命名空间。