23

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

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

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

6
  • Are you using strongly typed view Commented Jun 10, 2012 at 21:40
  • Yes........................... Commented Jun 10, 2012 at 21:41
  • 1
    What is the current id and why can't you pass it? Commented Jun 10, 2012 at 21:41
  • And what HTTP method do you want to use? You can easily specify FormMethod.Get or whatever instead of FormMethod.Post here if you want to. Commented Jun 10, 2012 at 21:42
  • 3
    Why not put a ',' and add a id attribute. You can append multiple atrributes like that. @using (Html.BeginForm("Edit", "Clients", FormMethod.Post, new { @class="example", id = Model.Id})) Is this you are looking for or what is the exact problem? Commented Jun 11, 2012 at 11:56

4 Answers 4

40

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.

See MSDN docs.

Sign up to request clarification or add additional context in comments.

2 Comments

And of course you can also pass @id="blah" in the 5th parameter object, which will have the completely different effect of setting the HTML id of the rendered form tag.
First two parameters can be null if you want to post to same action (Post method) of current controller like: @using(Html.BeginForm(null, null, new {Id=Model.Id}, FormMethod.Post, new {@class = "example"}))
21

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

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

1 Comment

Indeed it does.
2

Calling via an ActionLink from ControllerA

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

}

OR

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

}

Comments

0

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:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.