Avoid hard-coding controller and action names

前端 未结 5 804
攒了一身酷
攒了一身酷 2020-12-24 15:19

ASP.NET MVC seems to be encouraging me to use hard-coded strings to refer to controllers and actions.

For example, in a controller:

return RedirectT         


        
5条回答
  •  旧巷少年郎
    2020-12-24 16:08

    Not sure if somebody already added an extension method to one of the ASP.NET MVC related projects but here's a piece of code that you can use to create your own extension method:

    public RedirectToRouteResult RedirectToAction(Expression> action, RouteValueDictionary routeValues) where TController : Controller
        {
            RouteValueDictionary rv = Microsoft.Web.Mvc.Internal.ExpressionHelper.GetRouteValuesFromExpression(action);
    
            return RedirectToAction((string)rv["Action"], (string)rv["Controller"], routeValues ?? new RouteValueDictionary());
        }
    
        public ActionResult Index()
        {
            return RedirectToAction(x => x.Index(), null);
        }
    

    There's no parameters merging logic, so you'll have to add it by your own.

    UPDATE: @mccow002 added a similar solution a few seconds before me, so I think his solution should be accepted.

提交回复
热议问题