是否有一种方法在使用Asp时包含一个片段标识符。Net MVC ActionLink, RedirectToAction等等?

时间:2022-01-14 01:49:42

I want some links to include a fragment identifier. Like some of the URLs on this site:

我想要一些包含片段标识符的链接。像这个网站上的一些网址:

Debugging: IE6 + SSL + AJAX + post form = 404 error#5626

调试:IE6 + SSL + AJAX + post表单= 404错误#5626。

Is there a way to do this with any of the built-in methods in MVC? Or would I have to roll my own HTML helpers?

是否有一种方法可以使用MVC中的任何内置方法来实现这一点?或者我需要自己的HTML助手吗?

7 个解决方案

#1


5  

We're looking at including support for this in our next release.

我们将在下一次发布中考虑支持这一点。

#2


18  

As Brad Wilson wrote, you can build your own link in your views by simply concatenating strings. But to append a fragment name to a redirect generated via RedirectToAction (or similar) you'll need something like this:

正如Brad Wilson所写的,您可以通过连接字符串在视图中构建自己的链接。但是要将一个片段名附加到通过RedirectToAction(或类似的)生成的重定向中,您需要以下内容:

public class RedirectToRouteResultEx : RedirectToRouteResult {

    public RedirectToRouteResultEx(RouteValueDictionary values)
        : base(values) {
    }

    public RedirectToRouteResultEx(string routeName, RouteValueDictionary values)
        : base(routeName, values) {
    }

    public override void ExecuteResult(ControllerContext context) {
        var destination = new StringBuilder();

        var helper = new UrlHelper(context.RequestContext);
        destination.Append(helper.RouteUrl(RouteName, RouteValues));

        //Add href fragment if set
        if (!string.IsNullOrEmpty(Fragment)) {
            destination.AppendFormat("#{0}", Fragment);
        }

        context.HttpContext.Response.Redirect(destination.ToString(), false);
    }

    public string Fragment { get; set; }
}

public static class RedirectToRouteResultExtensions {
    public static RedirectToRouteResultEx AddFragment(this RedirectToRouteResult result, string fragment) {
        return new RedirectToRouteResultEx(result.RouteName, result.RouteValues) {
            Fragment = fragment
        };
    }
}

And then, in your controller, you'd call:

然后,在控制器中,你会调用:

return RedirectToAction("MyAction", "MyController")
       .AddFragment("fragment-name");

That should generate the URL correctly.

应该正确地生成URL。

#3


4  

In MVC3 (and possibly earlier I haven't checked), you can use UrlHelper.GenerateUrl passing in the fragment parameter. Here's a helper method I use to wrap the functionalityL

在MVC3中(可能更早的时候我还没有检查),您可以使用UrlHelper。GenerateUrl传入片段参数。下面是我用来包装functionalityL的助手方法

public static string Action(this UrlHelper url, string actionName, string controllerName, string fragment, object routeValues)
{
    return UrlHelper.GenerateUrl(
        routeName: null,
        actionName: actionName,
        controllerName: controllerName,
        routeValues: new System.Web.Routing.RouteValueDictionary(routeValues),
        fragment: fragment,
        protocol: null,
        hostName: null,
        routeCollection: url.RouteCollection,
        requestContext: url.RequestContext,
        includeImplicitMvcValues: true /*helps fill in the nulls above*/
    );
}

#4


3  

@Dominic,

@Dominic,

I'm almost positive that putting that in the route will cause routing issues.

我几乎肯定,把它放到路由中会导致路由问题。

@Ricky,

@Ricky,

Until MVC has support for this, you can be a little more "old school" about how you make your routes. For example, you can convert:

在MVC支持这一点之前,您可以对如何创建路由有更多的了解。例如,你可以转换:

<%= Html.ActionLink("Home", "Index") %>

into:

成:

<a href='<%= Url.Action("Index") %>#2345'>Home</a>

Or you can write your own helper that does essentially the same thing.

或者你也可以写你自己的助手来做同样的事情。

#5


1  

The short answer is: No. In ASP.NET MVC Preview 3 there's no first-class way for including an anchor in an action link. Unlike Rails' url_for :anchor, UrlHelper.GenerateUrl (and ActionLink, RedirectToAction and so on which use it) don't have a magic property name that lets you encode an anchor.

简短的回答是:不。在ASP。没有一种一流的方法可以在动作链接中包含锚点。不像Rails的url_for:anchor, UrlHelper。GenerateUrl(和ActionLink、RedirectToAction等使用它)没有可以让您对锚进行编码的神奇属性名。

As you point out, you could roll your own that does. This is probably the cleanest solution.

正如你所指出的,你可以用你自己的方式。这可能是最干净的解决方案。

Hackily, you could just include an anchor in a route and specify the value in your parameters hash:

简单地说,您可以在路径中包含一个锚点,并在参数哈希中指定值:

routes.MapRoute("WithTarget", "{controller}/{action}/{id}#{target}");
...
<%= Html.ActionLink("Home", "Index", new { target = "foo" })%>

This will generate a URL like /Home/Index/#foo. Unfortunately this doesn't play well with URL parameters, which appear at the end of the URL. So this hack is only workable in really simple circumstances where all of your parameters appear as URL path components.

这将生成一个URL,比如/Home/Index/#foo。不幸的是,这不能很好地处理URL参数,这些参数出现在URL的末尾。所以这个技巧只适用于非常简单的情况,即所有参数都显示为URL路径组件。

#6


0  

This is a client side solution but if you have jquery available you can do something like this.

这是一个客户端解决方案,但是如果您有jquery,您可以这样做。

<script language="javascript" type="text/javascript">
    $(function () {
        $('div.imageHolder > a').each(function () {
            $(this).attr('href', $(this).attr('href') + '#tab-works');
        });
    });
</script>

#7


0  

Fragment identifiers are supported in MVC 5. See ActionLink's overloads at https://msdn.microsoft.com/en-us/library/dd460522(v=vs.118).aspx and https://msdn.microsoft.com/en-us/library/dd492938(v=vs.118).aspx.

MVC 5支持片段标识符。参见ActionLink的重载:https://msdn.microsoft.com/en-us/library/dd460522(v=vs.118).aspx和https://msdn.microsoft.com/en-us/library/dd492938(v=vs.118).aspx。

#1


5  

We're looking at including support for this in our next release.

我们将在下一次发布中考虑支持这一点。

#2


18  

As Brad Wilson wrote, you can build your own link in your views by simply concatenating strings. But to append a fragment name to a redirect generated via RedirectToAction (or similar) you'll need something like this:

正如Brad Wilson所写的,您可以通过连接字符串在视图中构建自己的链接。但是要将一个片段名附加到通过RedirectToAction(或类似的)生成的重定向中,您需要以下内容:

public class RedirectToRouteResultEx : RedirectToRouteResult {

    public RedirectToRouteResultEx(RouteValueDictionary values)
        : base(values) {
    }

    public RedirectToRouteResultEx(string routeName, RouteValueDictionary values)
        : base(routeName, values) {
    }

    public override void ExecuteResult(ControllerContext context) {
        var destination = new StringBuilder();

        var helper = new UrlHelper(context.RequestContext);
        destination.Append(helper.RouteUrl(RouteName, RouteValues));

        //Add href fragment if set
        if (!string.IsNullOrEmpty(Fragment)) {
            destination.AppendFormat("#{0}", Fragment);
        }

        context.HttpContext.Response.Redirect(destination.ToString(), false);
    }

    public string Fragment { get; set; }
}

public static class RedirectToRouteResultExtensions {
    public static RedirectToRouteResultEx AddFragment(this RedirectToRouteResult result, string fragment) {
        return new RedirectToRouteResultEx(result.RouteName, result.RouteValues) {
            Fragment = fragment
        };
    }
}

And then, in your controller, you'd call:

然后,在控制器中,你会调用:

return RedirectToAction("MyAction", "MyController")
       .AddFragment("fragment-name");

That should generate the URL correctly.

应该正确地生成URL。

#3


4  

In MVC3 (and possibly earlier I haven't checked), you can use UrlHelper.GenerateUrl passing in the fragment parameter. Here's a helper method I use to wrap the functionalityL

在MVC3中(可能更早的时候我还没有检查),您可以使用UrlHelper。GenerateUrl传入片段参数。下面是我用来包装functionalityL的助手方法

public static string Action(this UrlHelper url, string actionName, string controllerName, string fragment, object routeValues)
{
    return UrlHelper.GenerateUrl(
        routeName: null,
        actionName: actionName,
        controllerName: controllerName,
        routeValues: new System.Web.Routing.RouteValueDictionary(routeValues),
        fragment: fragment,
        protocol: null,
        hostName: null,
        routeCollection: url.RouteCollection,
        requestContext: url.RequestContext,
        includeImplicitMvcValues: true /*helps fill in the nulls above*/
    );
}

#4


3  

@Dominic,

@Dominic,

I'm almost positive that putting that in the route will cause routing issues.

我几乎肯定,把它放到路由中会导致路由问题。

@Ricky,

@Ricky,

Until MVC has support for this, you can be a little more "old school" about how you make your routes. For example, you can convert:

在MVC支持这一点之前,您可以对如何创建路由有更多的了解。例如,你可以转换:

<%= Html.ActionLink("Home", "Index") %>

into:

成:

<a href='<%= Url.Action("Index") %>#2345'>Home</a>

Or you can write your own helper that does essentially the same thing.

或者你也可以写你自己的助手来做同样的事情。

#5


1  

The short answer is: No. In ASP.NET MVC Preview 3 there's no first-class way for including an anchor in an action link. Unlike Rails' url_for :anchor, UrlHelper.GenerateUrl (and ActionLink, RedirectToAction and so on which use it) don't have a magic property name that lets you encode an anchor.

简短的回答是:不。在ASP。没有一种一流的方法可以在动作链接中包含锚点。不像Rails的url_for:anchor, UrlHelper。GenerateUrl(和ActionLink、RedirectToAction等使用它)没有可以让您对锚进行编码的神奇属性名。

As you point out, you could roll your own that does. This is probably the cleanest solution.

正如你所指出的,你可以用你自己的方式。这可能是最干净的解决方案。

Hackily, you could just include an anchor in a route and specify the value in your parameters hash:

简单地说,您可以在路径中包含一个锚点,并在参数哈希中指定值:

routes.MapRoute("WithTarget", "{controller}/{action}/{id}#{target}");
...
<%= Html.ActionLink("Home", "Index", new { target = "foo" })%>

This will generate a URL like /Home/Index/#foo. Unfortunately this doesn't play well with URL parameters, which appear at the end of the URL. So this hack is only workable in really simple circumstances where all of your parameters appear as URL path components.

这将生成一个URL,比如/Home/Index/#foo。不幸的是,这不能很好地处理URL参数,这些参数出现在URL的末尾。所以这个技巧只适用于非常简单的情况,即所有参数都显示为URL路径组件。

#6


0  

This is a client side solution but if you have jquery available you can do something like this.

这是一个客户端解决方案,但是如果您有jquery,您可以这样做。

<script language="javascript" type="text/javascript">
    $(function () {
        $('div.imageHolder > a').each(function () {
            $(this).attr('href', $(this).attr('href') + '#tab-works');
        });
    });
</script>

#7


0  

Fragment identifiers are supported in MVC 5. See ActionLink's overloads at https://msdn.microsoft.com/en-us/library/dd460522(v=vs.118).aspx and https://msdn.microsoft.com/en-us/library/dd492938(v=vs.118).aspx.

MVC 5支持片段标识符。参见ActionLink的重载:https://msdn.microsoft.com/en-us/library/dd460522(v=vs.118).aspx和https://msdn.microsoft.com/en-us/library/dd492938(v=vs.118).aspx。