【问题标题】:MVC Razor - BeginForm with Anchor ActionMVC Razor - BeginForm 与锚点动作
【发布时间】:2017-11-13 23:39:02
【问题描述】:

我有一个靠近页面底部的联系表格,需要滚动才能到达;提交表单时,页面会重新加载,我需要页面在联系表单处转到锚点。当我更改 BeginForm 的操作时,锚点中的“#”被编码为“%23”——如何阻止这种形式的发生?

我需要它在不使用任何 JavaScript 的情况下运行。

@{
    using (Html.BeginForm(null, null, new { ReturnURL = "#contact" }, FormMethod.Post, new { novalidate = "novalidate" }))
    {
        //Fields...

        <button type="submit">Submit</button>
    }
}

上面的代码会返回如下的HTML,不会去锚点:

<form action="/en/Home/Contact?ReturnURL=%23contact" method="post" novalidate="novalidate"> 

虽然下面的 HTML 会(但我不知道如何用 Razor 生成它):

<form action="/en/Home/Contact?ReturnURL=#contact" method="post" novalidate="novalidate"> 

我也尝试了以下方法,但“#”总是被编码:

using (Html.BeginForm(null, null, new { ReturnURL = HttpUtility.HtmlDecode("#contact") }, FormMethod.Post, new { novalidate = "novalidate" }))

using (Html.BeginForm(null, null, new { ReturnURL = HttpUtility.UrlDecode("#contact") }, FormMethod.Post, new { novalidate = "novalidate" }))

using (Html.BeginForm(new { action = Url.Action("Index", "Home") + Html.Raw("Contact/#contact") }))

【问题讨论】:

标签: html asp.net-mvc razor encoding anchor


【解决方案1】:

似乎使用关键字“action”会覆盖表单的操作 - 以下代码是一种解决方案:

using (Html.BeginForm(null, null, FormMethod.Post, new { action = "#contact" }))

提交后,用户将被发送至site.com/#contact

对于表单不在 index/home/front page 上的网站,我使用以下内容来构建路由:

using (Html.BeginForm(null, null, FormMethod.Post, 
  new { action = string.Format("{0}/{1}#contact", 
        ViewContext.RouteData.Values["controller"], 
        ViewContext.RouteData.Values["action"])
  }))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 2021-03-23
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多