.NET MVCは強く型付けされたRedirectToActionを持っていますか?
-
22-08-2019 - |
質問
私は今のベータ版で滞在しながらRCを手放すことに決めたので、私は強く型付けされたRedirectToAction
が追加されているかどうかを知る方法はありません。誰もがそれを試してみましたが、強く型付けされたRedirectToAction
(そしておそらくActionLink
)があるRCでいますか?
解決
いいえ、それはしません。
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);
}
これは動作するはずです。
他のヒント
これは、多くのと一緒に、あなたのコントローラ上の拡張メソッドとしてを MVC Contribの中に含まれていますModelState取り扱い、テストなど、それが提供するものを、余分な依存関係に取っても価値があるため、他の強く型付けされたグッズます。
あなたはreturn RedirectToAction(nameof(Index));
を使用することができます。
あなたはフルMvcContribライブラリをしたくない場合は、 MvcNavigationHelpers NuGetパッケージます。
所属していません StackOverflow