19

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

4

4 回答 4

25

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

于 2009-12-01T16:26:12.353 回答
18

不,它没有。

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);
}

那应该行得通。

于 2009-02-08T16:36:44.323 回答
5

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

于 2017-03-04T09:47:23.033 回答
0

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

于 2017-03-04T04:04:09.473 回答