Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 621
Zack Avatar asked Sep 19 '09 17:09

Zack


People also ask

What is HTML BeginForm ()?

BeginForm(HtmlHelper) Writes an opening <form> tag to the response. The form uses the POST method, and the request is processed by the action method for the view. BeginForm(HtmlHelper, String, String, Object, FormMethod, Object)

What is difference between HTML BeginForm and ajax BeginForm?

Html. BeginForm() will create a form on the page that submits its values to the server as a synchronous HTTP request, refreshing the entire page in the process. Ajax. BeginForm() creates a form that submits its values using an asynchronous ajax request.

Which two objects can you passed as a parameter to the HTML helper Dot BeginForm method?

In the "BeginForm()" method we passed an action name and controller name so that the action method will be called that handles the post data request.


2 Answers

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.

like image 192
David Andres Avatar answered Oct 05 '22 02:10

David Andres


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

like image 43
Avi Pinto Avatar answered Oct 05 '22 03:10

Avi Pinto