带有绝对 URL 的 Html.BeginForm()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1965103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:41:42  来源:igfitidea点击:

Html.BeginForm() with an absolute URL?

htmlasp.net-mvcforms

提问by dale

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?

我需要将 POST 操作设为绝对 URL(例如,http://www.cnn.com)。有没有办法使用 Html.BeginForm() 助手并将其传递给 url?

回答by Nikita Ignatov

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 方法有几个重载。为了使用所需的 url 在表单标签上设置 action 属性,您需要使用以下 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.

由于您要发布到外部站点,因此无需设置 actionName 和 controllerName,只需将它们保留为 null。

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

This will not encode the action parameter.

这不会对动作参数进行编码。

回答by Aaronaught

All that the HtmlHelper.BeginFormmethod 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.

HtmlHelper.BeginForm方法所做的只是帮助您创建一个<form>以本地控制器为目标的标签。如果您要发布到外部站点,只需写出实际<form>标签,即

<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.

这里的所有都是它的。MVC 表单不像 ASP.NET WebForms 中的表单,在那里你有一堆 ViewState 和事件字段以及其他神奇的元素。它们只是普通的旧 HTML 表单。

回答by Bill.Zhuang

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,

检查 mvc 源代码,html.beginform 方法不仅只创建本机 html 表单,而且还添加了我想要的客户端验证,

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

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

所以这将是一个问题,我只是写我自己的扩展