Return 在 ASP.NET MVC 5 中提交表单后到相同的视图

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

我已经创建了一个联系表。在此联系表中,用户可以输入名字、姓氏、电话号码等数据。用户提交表单后,我执行服务器端验证。如果验证成功和不成功,我想将用户重定向回相同的视图。这没有问题。但是视图的滚动位置再次位于顶部。但是表格在最底部。用户应该直接再次显示表单。所以换句话说:我想 return 向用户显示相同的视图但保持滚动位置。我如何在 ASP.NET MVC 5 中实现这一点?

我的服务器端代码如下所示:

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

谢谢。

感谢 Natha Miller 的帮助。 解决方案: 在 ViewBag 中,您必须输入要跳回的部分。例如,这可以是控制器中的以下指令:

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

然后您必须检查 JavaScript 中的 .cshtml 文件是否设置了 ViewBag 中的 Section 变量。如果是这种情况,那么您必须跳转到特定位置。其工作方式如下:

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

解决方案来自一个已经在 Whosebug 上提出的问题。 Here 是它的 link。