2014-06-28 135 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