我有一个打印到屏幕上的数据列表。在屏幕底部(滚动),我有一个带有文本字段的表单,用户可以在其中输入数据。当他们单击提交并且表单无效时,错误显示正确,但用户现在正在寻找在页面的最顶部。因此,他们看不到页面底部有错误。我希望它跳转到页面底部的表单,以便用户可以看到发生了错误。
我考虑过使用 anchor ,但问题是;因为当我意识到表单无效时我已经在 Controller 中,所以我需要重定向回将主题标签附加到 url 的同一个 Controller 。在我看来,这不是什么好的做法,有点浪费。
有谁知道更好的方法吗?
最佳答案
执行此操作的一种方法是始终发布到 anchor ,并在 View 中确定放置 anchor 的位置。如果存在模型错误,则将命名 anchor 放置在页面底部,如果没有错误,则将 anchor 放置在页面顶部。使这变得复杂的一件事是没有采用 anchor 的 Html.BeginForm 重载。你可以像这样简单地实现它
<form action="@Url.Action("actionName", "controllerName")#anchor_name" method="post">
..... form contents .....
</form>
或者您可以编写自定义 HTML 帮助器
public static class FormExtensions
{
public static MvcForm CustomBeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, string fragment)
{
var formAction = UrlHelper.GenerateUrl(null, actionName, controllerName, htmlHelper.ViewContext.HttpContext.Request.Url.Scheme, null, fragment, null, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, true);
var builder = new TagBuilder("form");
builder.MergeAttribute("action", formAction);
builder.MergeAttribute("method", "post", true);
htmlHelper.ViewContext.Writer.Write(builder.ToString(TagRenderMode.StartTag));
return new MvcForm(htmlHelper.ViewContext);
}
}
然后你可以使用 @Html.CustomBeginForm('action', 'controller', 'anchor_name')
This question很有用并告知我的答案
关于.net - 表单发布 mvc3 .net 后跳转到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11855814/