1

I have a contact form that is near the bottom of the page, and requires scrolling to get to; when the form is submitted, the page is reloaded, and I need for the page to go to an anchor, at the contact form. When I change the action of the BeginForm, the '#' within the anchor is encoded to '%23' - how do I stop this form happening?

I need this to function without the use of any JavaScript.

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

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

The above code will return the following HTML, and will not go to the anchor:

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

While the following HTML would (but I don't know how to generate it with Razor):

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

I've also tried the following, but the '#' is always encoded:

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") }))
Luke
  • 33
  • 8
  • https://stackoverflow.com/questions/274586/including-an-anchor-tag-in-an-asp-net-mvc-html-actionlink try this – Danimal Sep 29 '17 at 14:48

1 Answers1

1

It seems that using the keyword 'action' overwrites the form's action - the following code is a solution:

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

On submission, the user will be sent to site.com/#contact

For sites where the form isn't on the index/home/front page, I've used the following to build a route:

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