简体   繁体   中英

Return to same view after form submit in ASP.NET MVC 5

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM