2011-03-04 60 views
0

使用asp.net的MVC 3.0我會做什麼,以提供以下路線含有問號的操作名稱?

public class ProductController : Controller 
{ 
    // ************************ 
    // URL : Product/Create 
    // ************************ 

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

    // ************************ 
    // URL : Product/Create?Page=Details 
    // ************************ 

    [ActionName("Create?Page=Details")] 
    public ActionResult CreateDetails() 
    { 
     return View(); 
    } 
} 

感謝

羅漢

回答

2
public class QueryStringConstraint : IRouteConstraint 
{ 
    public QueryStringConstraint(string value, bool ignoreCase = true) 
    { 
     Value = value; 
     IgnoreCase = ignoreCase; 
    } 

    public string Value { get; private set; } 
    public bool IgnoreCase { get; private set; } 

    public virtual bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 
     var currentValue = httpContext.Request.QueryString[parameterName]; 

     return IgnoreCase ? currentValue.ToLowerInvariant() == Value.ToLowerInvariant() : currentValue == Value; 
    } 
} 

routes.MapRoute("Create page details", "Product/Create", 
    new { controller = "Product", action = "CreateDetails" }, 
    new { page = new QueryStringConstraint("details") }); 

另外,如果你有這些行爲不同的車型,你可以做這樣的事情(與標準 「{控制器}/{行動}/{可選id}」 路線):

public class RequireRequestValueAttribute : ActionMethodSelectorAttribute 
{ 
    public RequireRequestValueAttribute(string name, string value = null, bool ignoreCase = true) 
    { 
     Name = name; 
     Value = value; 
     IgnoreCase = ignoreCase; 
    } 

    public string Name { get; private set; } 
    public string Value { get; private set; } 
    public bool IgnoreCase { get; private set; } 

    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) 
    { 
     var value = controllerContext.HttpContext.Request[Name]; 

     return value != null && (Value == null || (IgnoreCase ? Value.ToLowerInvariant() == value.ToLowerInvariant() : Value == value)); 
    } 
} 

[RequireRequestValue("Page", "Detail")] 
public ActionResult Create(ProductDetailModel model) 
{ 
    return View(model); 
} 
[RequireRequestValue("Page", "Overview")] 
public ActionResult Create(ProductOverviewModel model) 
{ 
    return View(model); 
} 
0

動作名不能包含問號。問號是指示查詢字符串開始的URL中的保留字符。

0

如果你不創建另一個動作呢?只需使用查詢字符串調用您的「創建」操作即可。

http://localhost/Home/Create?Page=Details 

public ActionResult Create() 
{ 
    var page = Request.QueryString["Page"]; 

    // do your stuff, or redirect here if you like 
    // return RedirectToAction("Create" + page); 

    return View(); 
} 
相關問題