Zack
Zack

Reputation: 2351

Best way to create form with Html.BeginForm() that should be SSL?

I have a form on a non-SSL page that I want to submit as SSL. I am creating the form using Html.BeginForm but that isn't required. It would also be nice if I could make it configuratble, so that i could have a flag that I set so that on the dev server or on my laptop I can turn the SSL off and turn it on in the production server.

I know that I could just make the entire URL a config item but I was hoping that I could make it more flexible so I could just have a true or false setting.

Upvotes: 7

Views: 4196

Answers (2)

Avi Pinto
Avi Pinto

Reputation: 4336

i know it's an old question, just a suggestion for a cleaner solution:

<form id="someLie" method="post" action="<%=Url.Action("action", "controller",new {}, YourConfigOrModel.UseSSL ? Uri.UriSchemeHttps : Uri.UriSchemeHttp) %>">
.. form elements..
</form>

this will render an absolute path containing the https://.. or a regular relative one for http

Upvotes: 3

David Andres
David Andres

Reputation: 31811

You can override the action attribute of the form created by Html.BeginForm.

<% 
   var actionURL = (Model.UseSSL ? "https://" : "http://") 
                   + Request.Url.Host + Request.Url.PathAndQuery;    

   using (
          Html.BeginForm(
                         "Action", 
                         "Controller", 
                         FormMethod.Post, 
                         new { @action = actionURL }
                        )
         )
%>

Note the use of the Model.UseSSL flag, which should be passed to this View by its Controller.

Upvotes: 6

Related Questions