开发者

Redirect route by route values

I have the default route in global.asax defined

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

I need to achieve this.

/somecontroller/edit/1 - when the id is开发者_如何学Go a number then let it go /somecontroller/edit/xxxx - when the id is a string then redirect it to /somecontroller/xxxx

and only when the action is called edit.


In RegisterRoutes method is url translated to name and value of controller, action and other parameters.
You can write your own map route logic - first line which is satisfied will be proceeded.

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

// empty url is mapping to Home/Index
routes.MapRoute(null, "", new { controller = "Home", action = "Index", id = UrlParameter.Optional });

// accepts "Whatever/Edit/number", where Whatever is controller name (ie Home/Edit/123)
routes.MapRoute(null,
      // first is controller name, then text "edit" and then parameter named id
      "{controller}/edit/{id}", 
      // we have to set action manually - it isn't set in url - {action} not set
      new { action = "edit"},  
      new { id = @"\d+" }      // id can be only from digits
    );


// action name is AFTER edit (ie Home/Edit/MyActionMethod)
routes.MapRoute(null, "{controller}/edit/{action}");

// default action is index -> /Home will map to Home/Index
routes.MapRoute(null, "{controller}", new{action="Index"}); 

// accepts controller/action (Home/Index or Home/Edit)
routes.MapRoute(null, "{controller}/{action}");                 

// controller_name/action_name/whatever, where whatever is action method's id parameter (could be string)
routes.MapRoute(null, "{controller}/{action}/{id}");            


Probably you can't handle it only by routes. You need to check it inside Edit action and redirect to the Index action in case of string value, otherwise handle edit action.

routing constraint

public class IsIntegerConstraint : IRouteConstraint
{
    #region IRouteConstraint Members

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        int result;

        return int.TryParse(values[parameterName].ToString(), out result);
    }

    #endregion
}

routes

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
            new { id = new IsIntegerConstraint() }
        );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜