属性路由选择错误MVC 5

问题描述:

我试图用多个可选参数路由动作,但它不工作。我分享我的代码,请指导我。属性路由选择错误MVC 5

[HandleError] 
[RouteArea("Admin", AreaPrefix = "sp-admin")] 
[RoutePrefix("abc-system")] 
[Route("{action}")] 
public class AbcController : Controller 
{ 
    [Route("list/{id:int?}/{PersonID?}/{ref?}")] 
    public async Task<ActionResult> Index(int? id, int? PersonID, string @ref) 
    { 
     return view(); 
    } 
} 

这不会这样工作 http://anylocallink.com/sp-admin/abc-system/list/2/details 但像他这样 http://anylocallink.com/sp-admin/abc-system/list/2/3/details

我想,如果链接有任何可选参数,它的工作工作。 请指导我

+1

路线应该如何知道你想要id与personID中的“2”?这根本无法完成。 – Shoe 2014-09-04 03:41:17

+0

@Shoe有没有办法做到这一点? – Anony 2014-09-04 08:45:29

这将无法正常工作,因为路线不会知道在哪里放int参数。你可以做这样的事情,虽然

[Route("list/{type}/{id}/{ref?}")] 
public async Task<ActionResult> Index(string type, int id, string @ref) 
{ 
    if(type == "Person"){ ... } 
    else { ... } 

    return View(); 
} 

然后你就可以对路线做

list/Person/1/Details 
list/ID/2/Details 

您可以指定“阿尔法”为约束的@ref操作参数,有两个动作像如下:

[Route("list/{id:int?}/{ref:alpha?}")] 
public async Task<ActionResult> Index(int? id, string @ref) 
{ 
    return await Index(id, null, @ref); 
} 

[Route("list/{id:int?}/{personId:int?}/{ref:alpha?}")] 
public async Task<ActionResult> Index(int? id, int? personId, string @ref) 
{ 
    return View(); 
} 

这对两种情况均适用。我更喜欢这个,因为我不必 一次又一次地修改我的路线。

+0

它只适用于身份证不适用PersonID – Anony 2014-09-05 01:11:58

+0

你可以试试这个 https://[email protected]/viraj_siriwardana/routeattributingquiz-25655735.git – 2014-09-05 01:28:21

+0

否则你可以将两条路线添加到同一个动作。但我认为你应该修改你的行动方法设计,而不是试图将所有选项都放在一个。 – 2014-09-05 05:39:32