Search code examples
asp.net-corescrollto

ASPNET Core ScrollTo After Post


I have ASPNETCore application with a model that successfully sends email and returns a message to the browser.

    [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();
    }

After the post, I am trying to scroll back to near bottom of the page where the contact form is to show the message sent feedback. I have tried many examples and all just end up with the page at the top after postback not back to the contact form position. Any help appreciated.

Kind Regards,

Neil


Solution

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

    To achieve the requirement of maintaining the scroll position after the post, you can refer to the following approach to store the scroll position in localStorage while user submitting the form then retrieve it and dynamically reset the scroll position after page reloaded.

    Html Code

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

    JS Code

    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');
    });
    

    Test Result

    enter image description here