在MVC3问题中键入安全URL操作

时间:2012-09-03 08:10:03

标签: c# .net asp.net-mvc asp.net-mvc-3

我不喜欢Url.Action(“string”,“string”)因此写下面的扩展方法

public static string Action<TController>(this UrlHelper urlHelper, Expression<Func<TController, object>> actionExpression)
{
    var controllerName = typeof(TController).GetControllerName();
    var actionName = actionExpression.GetActionName();

    return urlHelper.Action(actionName, controllerName);
}

我在剃须刀视图中使用它,如下所示:

@{Url.Action<ClientController>(action => action.ClientDetails());}

它不会渲染任何东西。我在任何地方犯了错误,或者我错过了什么?是否可以这样做,因为我喜欢Type Safe性质,而不是硬编码动作名称和控制器?

1 个答案:

答案 0 :(得分:1)

使用括号表示代码块。使用括号(见下文)是一个显式表达式。表达式将作为HTML的一部分输出,但代码块不会。

@(Url.Action<ClientController>(action => action.ClientDetails()))

Check out this SO post for a more complete answer.