【问题标题】:Does .NET MVC have a strongly typed RedirectToAction?.NET MVC 是否具有强类型的 RedirectToAction?
【发布时间】:2010-10-06 06:35:36
【问题描述】:

由于我决定暂时放弃 RC 并继续使用 Beta,因此我无法知道是否添加了强类型 RedirectToAction。有没有人尝试过,RC 中有没有强类型的RedirectToAction(可能还有ActionLink)?

【问题讨论】:

  • 您应该将接受的答案更改为@Darrell Mozingo 的答案;因为 RedirectToAction 确实在 Futures 程序集中。

标签: asp.net-mvc mvccontrib url-redirection


【解决方案1】:

这也包含在MVC Contrib 中,作为控制器上的扩展方法,以及许多其他用于 ModelState 处理、测试等的强类型好东西。它提供的额外依赖是非常值得的。

【讨论】:

    【解决方案2】:

    不,它没有。

    protected RedirectToRouteResult RedirectToAction<T>(Expression<Action<T>> action, RouteValueDictionary values) where T : Controller
    {
        var body = action.Body as MethodCallExpression;
    
        if (body == null)
        {
            throw new ArgumentException("Expression must be a method call.");
        }
    
        if (body.Object != action.Parameters[0])
        {
            throw new ArgumentException("Method call must target lambda argument.");
        }
    
        string actionName = body.Method.Name;
    
        var attributes = body.Method.GetCustomAttributes(typeof(ActionNameAttribute), false);
        if (attributes.Length > 0)
        {
            var actionNameAttr = (ActionNameAttribute)attributes[0];
            actionName = actionNameAttr.Name;
        }
    
        string controllerName = typeof(T).Name;
    
        if (controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
        {
            controllerName = controllerName.Remove(controllerName.Length - 10, 10);
        }
    
        RouteValueDictionary defaults = LinkBuilder.BuildParameterValuesFromExpression(body) ?? new RouteValueDictionary();
    
        values = values ?? new RouteValueDictionary();
        values.Add("controller", controllerName);
        values.Add("action", actionName);
    
        if (defaults != null)
        {
            foreach (var pair in defaults.Where(p => p.Value != null))
            {
                values.Add(pair.Key, pair.Value);
            }
        }
    
        return new RedirectToRouteResult(values);
    }
    

    应该可以的。

    【讨论】:

    • 这是否存在于 Futures dll 中?我找不到它,如果它有?我也想知道为什么错过了??
    • 乍得..这怎么会成为Controller类的扩展方法?
    • 整个 MVC 框架应该是这样的强类型,我希望他们能抛弃魔术字符串,它就是“DataSets”。感谢Chad的代码。
    • 依赖于“LinkBuilder”类,这是定制代码吗?
    • LinkBuilder 是什么?
    【解决方案3】:

    您可以使用return RedirectToAction(nameof(Index));

    【讨论】:

      【解决方案4】:

      如果您不想要完整的 MvcContrib 库,您可以使用 MvcNavigationHelpers NuGet 包获得此功能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-27
        • 1970-01-01
        • 2011-01-20
        • 1970-01-01
        • 2011-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多