加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – .NET MVC是否有强类型的RedirectToAction?

发布时间:2020-12-16 00:44:47 所属栏目:asp.Net 来源:网络整理
导读:既然我决定让RC在现在停留在Beta版的时候,我无法知道是否添加了强类型的RedirectToAction。有没有人尝试过,在RC中有强类型的RedirectToAction(也可能是ActionLink)? 解决方法 不,没有。 protected RedirectToRouteResult RedirectToActionT(ExpressionAc
既然我决定让RC在现在停留在Beta版的时候,我无法知道是否添加了强类型的RedirectToAction。有没有人尝试过,在RC中有强类型的RedirectToAction(也可能是ActionLink)?

解决方法

不,没有。
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);
}

这应该工作。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读