URL格式动作,而ViewContext [英] Url Form Action Without ViewContext

查看:104
本文介绍了URL格式动作,而ViewContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能得到一个动作的URL不知道ViewContext(例如,在一个控制器)?事情是这样的:

Is it possible to get a URL from an action without knowing ViewContext (e.g., in a controller)? Something like this:

LinkBuilder.BuildUrlFromExpression(ViewContext context, Expression<Action<T>> action)

...但使用Controller.RouteData代替ViewContext。我似乎对这个金属块。

...but using Controller.RouteData instead of ViewContext. I seem to have metal block on this.

推荐答案

下面是我如何做到这一点的单元测试:

Here's how I do it in a unit test:

    private string RouteValueDictionaryToUrl(RouteValueDictionary rvd)
    {
        var context = MvcMockHelpers.FakeHttpContext("~/");
        // _routes is a RouteCollection
        var vpd = _routes.GetVirtualPath(
            new RequestContext(context, _
                routes.GetRouteData(context)), rvd);
        return vpd.VirtualPath;
    }

每评论,我会适应的控制器:

Per comments, I'll adapt to a controller:

string path = RouteTable.Routes.GetVirtualPath(
    new RequestContext(HttpContext, 
        RouteTable.Routes.GetRouteData(HttpContext)),
    new RouteValueDictionary( 
        new { controller = "Foo",
              action = "Bar" })).VirtualPath;

用真实姓名替换富和栏。这是把我的头顶部,所以我不能保证这是最有效的解决方案成为可能,但它应该让你在正确的轨道上。

Replace "Foo" and "Bar" with real names. This is off the top of my head, so I can't guarantee that it's the most efficient solution possible, but it should get you on the right track.

这篇关于URL格式动作,而ViewContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆