2014-06-28 139 views
0

最近我参加了采访,他询问了mvc中的动态路由。mvc中的动态路由

问题是如何根据参数字符串或int动态路由某些操作方法。

例如:

Public ActionResult Add(datatype variable) 
{ 
    //depending upon the Value he was asking how to redirect. 
} 

回答

4

重定向不会被路由处理,它是由被执行的操作处理。

我想他的意思是,你如何创建路由规则执行行动Foo如果数据类型为string,并且如果数据类型是int你如何执行行动Bar

您使用Routing Constraints,下面我添加了所有支持的约束的屏幕截图。

这是你将如何使用它们

public class HomeController: Controller 
{ 
    // foobar.com/home/123 
    [Route("home/{id:int}")] 
    public ActionResult Foo(int id) 
    { 
     return this.View(); 
    } 

    // foobar.com/home/onetwothree 
    [Route("home/{id:alpha}")] 
    public ActionResult Bar(string id) 
    { 
     return this.View(); 
    } 
} 

更多信息,可以发现here

List of supported routing constraints