如何在使用HTML时保持滚动位置。在Asp.Net MVC ActionLink吗?

时间:2022-12-02 11:33:21

I have the following code:

我有以下代码:

<a href="@Url.Action("Approve", new {id = item.Id})">Approve</a>

This calls an Action method in my controller updates the approval status of the record and then:

这调用我的控制器中的一个操作方法,更新记录的批准状态,然后:

return RedirectToAction("Index");

As expected, the page always refreshes to the top. Is there a way to maintain the scroll position to where I clicked the hyperlink. I have checked similar posts, but the ones I have seen referred to forms. Ultimately I will use JQuery/Ajax. However at present I want to see if there was a simple method that could be used like an HTML attribute.

正如预期的那样,页面总是刷新到顶部。是否有一种方法可以保持滚动位置到我点击超链接的位置。我也检查过类似的帖子,但是我看过的帖子都是表单。最终我将使用JQuery/Ajax。然而,目前我想看看是否有一种简单的方法可以像HTML属性一样使用。

Many thanks.

多谢。

1 个解决方案

#1


2  

You can name the anchor tag and refer to the name in the href using the hash notation:

您可以使用哈希表示法命名锚标记并引用href中的名称:

<a href="@Url.Action("Approve", new { id = item.Id })" id="@( item.Id )" name="@( item.Id )">Approve</a>

And then in your action method:

然后在你的行动方法中:

string redirectUrl =
    string.Format(
        "{0}#{1}",
        Url.Action("Index"),
        id);

return new RedirectResult(redirectUrl);

Just make sure your id is a value HTML id (nearly anything can be a valid id in HTML5, however rules apply for the naming of ids for earlier HTML versions). If in doubt, prefix it with something like 'aid-' (approval id), etc. before using in the HTML.

只需确保您的id是一个值HTML id(在HTML5中几乎任何东西都可以是一个有效的id,但是规则适用于早期HTML版本的id的命名)。如果有疑问,在使用HTML之前,在它前面加上“aid-”(approval id)等前缀。

Otherwise, like you've already identified, your best bet is to use an AJAX call to make the approval. This way you stay exactly where you are on the page.

否则,就像您已经确定的那样,最好的方法是使用AJAX调用来获得批准。这样你就能保持你在页面上的位置。

#1


2  

You can name the anchor tag and refer to the name in the href using the hash notation:

您可以使用哈希表示法命名锚标记并引用href中的名称:

<a href="@Url.Action("Approve", new { id = item.Id })" id="@( item.Id )" name="@( item.Id )">Approve</a>

And then in your action method:

然后在你的行动方法中:

string redirectUrl =
    string.Format(
        "{0}#{1}",
        Url.Action("Index"),
        id);

return new RedirectResult(redirectUrl);

Just make sure your id is a value HTML id (nearly anything can be a valid id in HTML5, however rules apply for the naming of ids for earlier HTML versions). If in doubt, prefix it with something like 'aid-' (approval id), etc. before using in the HTML.

只需确保您的id是一个值HTML id(在HTML5中几乎任何东西都可以是一个有效的id,但是规则适用于早期HTML版本的id的命名)。如果有疑问,在使用HTML之前,在它前面加上“aid-”(approval id)等前缀。

Otherwise, like you've already identified, your best bet is to use an AJAX call to make the approval. This way you stay exactly where you are on the page.

否则,就像您已经确定的那样,最好的方法是使用AJAX调用来获得批准。这样你就能保持你在页面上的位置。