C# 带有 html 属性的 Html.BeginForm asp.net mvc4

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10972558/
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-09 15:58:37  来源:igfitidea点击:

Html.BeginForm with html attributes asp.net mvc4

c#razorasp.net-mvc-4

提问by Irakli Lekishvili

I have Edit Action with Html.BeginForm. How can I add HTML attributes?

我有编辑操作Html.BeginForm。如何添加 HTML 属性?

I know only one way:

我只知道一种方法:

@using (Html.BeginForm("Edit", "Clients", FormMethod.Post, new { @class="example"})) {

}

but if I use this method I cannot pass current ID

但是如果我使用这种方法,我将无法传递当前的 ID

Is it possible to add HTML attributes to form without modifying action URL?

是否可以在不修改操作 URL 的情况下向表单添加 HTML 属性?

采纳答案by Ross McNab

The override you need is:

您需要的覆盖是:

@using( Html.BeginForm("Edit", "Clients", new { Id=Model.Id},
                       FormMethod.Post, new { @class = "example" } ) )
{
}
  • Route values like "id" are passed as the third parameter.
  • HTML attributes like "class" are passed as the fifth parameter.
  • 像“id”这样的路由值作为第三个参数传递。
  • 像“class”这样的 HTML 属性作为第五个参数传递。

See MSDNdocs.

请参阅MSDN文档。

回答by Oracular Man

Calling via an ActionLink from ControllerA

通过 ControllerA 的 ActionLink 调用

@using (Html.BeginForm("Create",
    "StudentPChoice",
    new { StudentPChoiceId = Model.StudentPChoiceId },
    FormMethod.Post))
{

}

OR

或者

@using (Html.BeginForm("Create",
    "ControllerB",
    new { ControllerBId = Model.ControllerAId },
    FormMethod.Post))
{

}

回答by D Monk

The Action and Controller parameters can also be null to use the default action:

Action 和 Controller 参数也可以为 null 以使用默认操作:

Html.BeginForm( null, null, FormMethod.Post, new { id=”formname”, @class="formclass" })

回答by Mayer Spitzer

If this might be helpful for some people, this works for me:

如果这可能对某些人有帮助,这对我有用:

@using (Html.BeginForm("RefreshData", "Home", FormMethod.Post, 
        new { Id = "timerangeId", @name = "timerange" }))
    {
        // form elements and input
    }

In Javascript:

在 JavaScript 中:

document.getElementById("timerangeId").submit();