简体   繁体   English

在 ASP.NET MVC 5 中提交表单后返回到同一视图

[英]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?我如何在 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.感谢 Natha Miller 的帮助。 The solution: In the ViewBag you have to enter the section you want to jump back to.解决方案:在 ViewBag 中,您必须输入要跳回的部分。 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.然后,如果设置了 ViewBag 中的 Section 变量,则必须在 JavaScript 中检入 .cshtml 文件。 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.解决方案来自 Stackoverflow 上已经提出的一个问题。 Here is the link to it. 是它的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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