MVC3区域路由冲突

时间:2012-05-11 09:39:11

标签: asp.net-mvc-3 exception asp.net-mvc-routing

问题:我希望我的路线像那样

/ admin / main / category / 1 - > 1 ==?page = 1 我不希望看到page = 1

我的控制器

public class MainController : BaseController
{
    private const int PageSize = 5; //pager view size

    [Inject]
    public ICategoryRepository CategoryRepository { get; set; }

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Category(int page)
    {
        //int pageIndex = page.HasValue ? page.Value : 1;
        int pageIndex = page != 0 ? page : 1; 
        return View("Category", CategoryViewModelFactory(pageIndex));
    }

    /*
     *Helper: private instance/static methods
     ======================================================================*/
    private CategoryViewModel CategoryViewModelFactory(int pageIndex) //generate viewmodel category result on pager request
    {
        return new CategoryViewModel
        {
            Categories = CategoryRepository.GetActiveCategoriesListDescending().ToPagedList(pageIndex, PageSize)
        };
    }
}



  public class AdminAreaRegistration : AreaRegistration
  {
        public override string AreaName
        {
            get
            {
                return "admin";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRouteLowercase(
                "AdminCategoryListView", 
                "admin/{controller}/{action}/{page}",
                new { controller = "Category", action = "Category", page = "1" },
                new { id = @"\d+" },
                new[] { "WebUI.Areas.Admin.Controllers" }
            );
        }
    }

My Exception:
  

参数字典包含参数“page”的空条目   非可空类型'System.Int32'的方法   'System.Web.Mvc.ActionResult类别(Int32)'中   'WebUI.Areas.Admin.Controllers.MainController'。可选参数   必须是引用类型,可空类型,或声明为   可选参数。参数名称:参数

提前谢谢大家。

1 个答案:

答案 0 :(得分:1)

确保在管理区域路由注册中您已定义{page}路由令牌,而不是默认生成的{id}

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{page}",
        new { action = "Index", page = UrlParameter.Optional }
    );
}

现在,当您生成链接时,请确保指定此参数:

@Html.ActionLink(
    "go to page 5",                         // linkText
    "category",                             // actionName
    "main",                                 // controllerName
    new { area = "admin", page = "5" },     // routeValues
    null                                    // htmlAttributes
)

会发出:

<a href="/Admin/main/category/5">go to page 5</a>

当请求此URL时,将调用Category操作并传递page=5参数。