包含问号的动作名称?

时间:2011-03-04 02:59:31

标签: asp.net-mvc-3

使用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();
    }
}

由于

罗汉

3 个答案:

答案 0 :(得分: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") });

或者,如果您为这些操作设置了不同的模型,则可以执行以下操作(使用标准的“{controller} / {action} / {optional 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);
}

答案 1 :(得分:0)

操作名称不能包含问号。问号是URL中的保留字符,表示查询字符串的开头。

答案 2 :(得分: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();
}