加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.NET MVC – 将表单发布到html书签?

发布时间:2020-12-16 07:31:29 所属栏目:asp.Net 来源:网络整理
导读:使用这样的表单时: h2%:Model.EulaTitle %/h2p%=Model.EulaHtml %/pa name="errors"/a%:Html.ValidationSummary()%div style="text-align:center;"% using (Html.BeginForm()) { %%:Html.HiddenFor(model = model.SourceUrl)%%:Html.HiddenFor(model = mode
使用这样的表单时:

<h2>
<%:Model.EulaTitle %>
</h2>
<p>
<%=Model.EulaHtml %>
</p>
<a name="errors"></a>
<%:Html.ValidationSummary()%>


<div style="text-align:center;">
<% using (Html.BeginForm())
   { %>

<%:Html.HiddenFor(model => model.SourceUrl)%>
<%:Html.HiddenFor(model => model.EulaId)%>


<a name="accept"></a>
<div style="text-align:center;">
<%:Html.CheckBoxFor(model => model.Accepted)%>
<%:Html.LabelFor(model => model.Accepted)%>
</div>
<input type="submit" value="Submit">
<% } %>
</div>

我需要页面在发布时滚动到#errors. Model.EulaHtml包含一些长度的EULA文本,我更希望用户不必手动向下滚动以查看错误消息,如果他们发布页面而不接受协议.

如果控制器在Post上检测到ModelState.IsValid,则会重定向到另一个页面.如果没有,我需要留在此页面,但滚动到#errors书签锚标记.

我想过只是在表单动作的url末尾添加’#errors’,但是我会在潜在危险的行中收到错误….(‘%’).我可能错误地编码了哈希标记.其他人不得不处理这个?我们正在处理对浏览器兼容性的非常严格的要求(IE6和其他一切在阳光下),所以我尽量避免使用JavaScript.

更新

我收到的错误是:

A potentially dangerous Request.Path value was detected from the client (%).

我修改了Html.BeginForm()调用

<% using (Html.BeginForm(new { @action="#errors" }))
   { %>

结果URL是:

http://..../TheControllerName/Eula/%2523errors/

我还注意到,当我以这种方式设置action属性时,传递的一些queryString参数会消失. (这并不奇怪,但对我来说,没有任何解决办法对我来说很明显)

解决方法

试试这样:

<form action="<%: Url.Action("actionName","controllerName") %>#errors" method="post">

    <%:Html.HiddenFor(model => model.SourceUrl)%>
    <%:Html.HiddenFor(model => model.EulaId)%>


    <a name="accept"></a>
    <div style="text-align:center;">
    <%:Html.CheckBoxFor(model => model.Accepted)%>
    <%:Html.LabelFor(model => model.Accepted)%>
    </div>
    <input type="submit" value="Submit">

</form>

您还可以编写一个可以执行此任务的自定义HTML帮助程序:

public static class FormExtensions
{
    public static MvcForm MyBeginForm(this HtmlHelper htmlHelper,string actionName,string controllerName,string fragment)
    {
        var formAction = UrlHelper.GenerateUrl(null,actionName,controllerName,htmlHelper.ViewContext.HttpContext.Request.Url.Scheme,null,fragment,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);
    }
}

然后:

<% using (Html.MyBeginForm("index","home","errors")) { %>
    ...
<% }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读