没有 ViewContext 的 URL 表单操作 [英] Url Form Action Without ViewContext

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

问题描述

是否可以在不知道 ViewContext 的情况下从操作中获取 URL(例如,在控制器中)?像这样:

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;

用真实姓名替换Foo"和Bar".这是我的想法,所以我不能保证它是最有效的解决方案,但它应该能让你走上正轨.

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.

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

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