7

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.

2 Answers 2

6

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.

4
  • this might be what I need. let me give it a try!!
    – Zack
    Sep 19, 2009 at 18:10
  • ActionLink renders an anchor tag. Is there something that will return the url but have the same option of specifying the protocol?
    – Zack
    Sep 19, 2009 at 18:15
  • I edited the post. I believe you may be able to override the forms action itself. If that doesn't work, you can render the form tag yourself without Html.BeginForm, in which case you can control its action setting however you like. Sep 19, 2009 at 18:19
  • I ended up writing out the form element and filling in the action attribute from a string I put togeter using Request.Url.Host, ResolveUrl("~"), and a config flag to tell me whether to use http or https. in your suggestion I think the actionURL just overrided the Action and Controller you set. Also, using PathAndQuery isn't the URL I wanted to post to, so those kindof made using BeginForm pointless even though that is what I wanted to do. But this got me close enough.
    – Zack
    Oct 9, 2009 at 17:35
3

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

1
  • 3
    I've tried something similar to this and I lost the unobtrusive validation for the form.
    – gt124
    Sep 26, 2011 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.