Html.BeginForm() with an absolute URL?
Asked Answered
P

3

38

I need to have the POST action be to an absolute URL (e.g., http://www.cnn.com). Is there a way to use Html.BeginForm() helper and pass it the url?

Postmistress answered 27/12, 2009 at 3:51 Comment(0)
J
76

BeginForm method has several overloads. In order to set the action attribute on the form tag with the desired url, you need to use following overload of BeginForm:

BeginForm(String, String, FormMethod, IDictionary<String, Object>)
// here are the parameter names:
BeginForm(actionName, controllerName, method, htmlAttributes)

Since you want to post to an external site, there is no need to set actionName and controllerName, just leave them as null.

@Html.BeginForm(
   null, null, FormMethod.Post, new {@action="http://cnn.com/post"}
)

This will not encode the action parameter.

Jaeger answered 20/7, 2011 at 23:58 Comment(0)
E
17

All that the HtmlHelper.BeginForm method does is help you to create a <form> tag that targets a local controller. If you're posting to an external site, just write out the actual <form> tag, i.e.

<form action="http://www.example.com/someaction" method="post">
    Actual form content in here
</form>

That's all there is to it. MVC forms are not like the forms in ASP.NET WebForms where you have a bunch of ViewState and event fields and other magical elements. They're just regular old HTML forms.

Elegant answered 27/12, 2009 at 4:4 Comment(5)
Yeh, I did this. But I was just wondering if I was missing something in MVC (coming from RoR Land, there is a form {url=()} method. Thx.Postmistress
there may be some thins related to validation that don't get created for you if you manually create the form - so watch out if you're using the MVC validation with jQueryCasuistry
As simon weaver pointed out, if you don't use the HtmlHelper validation framework does not work. I encountered this problem myselfSqueteague
And if you want the validation also, use @{ViewContext.FormContext = new FormContext(); } where you use the begin form and @{ViewContext.FormContext = null; } wherever you should close the using of the beginform.Squeteague
Simon_Weaver's and Zasz's comments are unbelievably useful for anyone considering following Aaronaught's advice.Makhachkala
P
0

check the mvc source code, html.beginform method not only create the native html form only, but also add sth for client validation which just i want,

if (htmlHelper.ViewContext.ClientValidationEnabled) 
{
    htmlHelper.ViewContext.FormContext.FormId = tagBuilder.Attributes["id"];
}

so it will be a problem, i just write my own extension

Philps answered 17/8, 2010 at 11:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.