1

I have created a contact form. In this contact form the user can enter data such as first name, last name, telephone number and so on. After the user submits the form I execute a server-side validation. I would like to redirect the user back to the same view if the validation was successful and unsuccessful. This works without problems. But the scroll position of the view is at the top again. But the form is at the very bottom. The user should get the form displayed again directly. So in other words: I want to return the same view to the user but keep the scroll position. How do I achieve this in ASP.NET MVC 5?

My server-side code looks like this:

public ActionResult Contact(ServiceModel model)
        {
            if (ModelState.IsValid)
            {
                ViewBag.SuccessMessage = " succeeded";
                return View("Index");
            }
            else
            {
                if (!this.IsCaptchaValid(""))
                {
                    ViewBag.ErrorMessage = "Error. Try again.";
                }
                return View("Index", model);
            }
        }

Thank you.

VillageTech
  • 1,968
  • 8
  • 18
Ali
  • 410
  • 5
  • 21
  • Check out [this SO answer](https://stackoverflow.com/a/10690511/12309486) – Nathan Miller Jan 09 '20 at 20:25
  • Nice. Works fine for me. But can I somehow pass the model in the RedirectResult function, too? Because I need to for the validation. I need the model to post the validation-error-messages if the validation went wrong. – Ali Jan 09 '20 at 20:39
  • 1
    Then it might be easiest to use a regular `return View("Index", model)` and [this SO answer](https://stackoverflow.com/a/15906458/12309486), which requires adding a property to the `ViewBag` and referencing it from JS. – Nathan Miller Jan 09 '20 at 21:06

1 Answers1

1

Thanks Natha Miller for your help. The solution: In the ViewBag you have to enter the section you want to jump back to. This can be for example the following instruction in the controller:

ViewBag.Section = "mySection"; //This refers to the element in the .cshtml page that has the ID 'mySection'.

Then you have to check in the .cshtml file in JavaScript if the Section variable in the ViewBag is set. If this is the case then you have to jump to the certain position. This works as follows:

@if (ViewBag.Section!=null)
{
    <script>
        $(function () {              
                window.location.hash = '#@ViewBag.Section';
        });
    </script>
}

The solution comes from a question that was already asked on Stackoverflow. Here is the link to it.

Ali
  • 410
  • 5
  • 21