Post 之后的 ASPNET Core ScrollTo

ASPNET Core ScrollTo After Post

我有一个 ASPNETCore 应用程序,它的模型可以成功地向浏览器发送电子邮件和 returns 一条消息。

    [HttpPost]
    public IActionResult Index(IndexViewModel model)
    {
        if (ModelState.IsValid)
        {
            try
            {
                // Send the email
                _mailService.SendMessage(model.Email, model.Subject, $"From: {model.Name} - {model.Email}, Message: {model.Message}");
                ViewBag.SendMessageClass = "p-3 mb-2 bg-success text-white rounded";
                ViewBag.UserMessage = $"Nice to hear from you {model.Name}, your message was sent successfully";
                ViewBag.JumpToDivId = "#contact_form";
                ModelState.Clear();
            }
            catch (Exception ex)
            {
                ViewBag.SendMessageClass = "p-3 mb-2 bg-danger text-white rounded";
                ViewBag.UserMessage = $"Whoops {model.Name}, we were unable to send the message, return code was {ex.ToString()}.";
                ViewBag.JumpToDivId = "#contact_form";
            }
        }

        return View();
    }

在 post 之后,我试图滚动回页面底部附近的联系表单,以显示已发送的反馈消息。我已经尝试了很多示例,但都只是在 post 返回后页面位于顶部,而不是返回到联系表单位置。任何帮助表示赞赏。

亲切的问候,

尼尔

trying to scroll back to near bottom of the page where the contact form is to show the message sent feedback

为了达到post后滚动位置保持不变的需求,可以参考下面的方法,在用户提交表单时将滚动位置存储在localStorage中,然后动态获取重新加载页面后重置滚动位置。

Html代码

<form>
    input fields here
    <br />
    ...
    <br />
    <input type="submit" value="Submit" onclick="maintainscrollposition()" />
</form>

JS代码

function maintainscrollposition() {
    var y = window.scrollY
    console.log(y);
    localStorage.setItem('topposition', y);
}

$(function () {
    var top = localStorage.getItem('topposition');
    window.scroll(0, top);
    localStorage.removeItem('topposition');
});

测试结果