85

How do I give a name to a form in ASP.NET MVC using Html.BeginForm()? I want only the name, not the action or controller name because I want to post it through Javascript. I think it should be something like Html.BeginForm(id = "frm").

I tried the following:

Html.BeginForm(null,null,new{id="frm",name="frm})

Html.BeginForm(new{@id="frm",@name="frm})

But the above code produces output like this:

<form action="/Main/Index/Id?name=Id" method="post">
Geert Immerzeel
  • 564
  • 4
  • 21
user426306
  • 903
  • 1
  • 7
  • 11

4 Answers4

145
Html.BeginForm(null, null, FormMethod.Get, new { name = "frm", id = "frm" })

You'll need to catch the form submit with your JavaScript

BritishDeveloper
  • 13,219
  • 9
  • 52
  • 62
9

Using MVC2, this is what worked for me:

<% using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new {@id = "myForm", @name = "myForm"})) {%>
0
@HTML.BeginForm("Target-ViewName where you want to post the page","Controller Name",new {@name="Name of the Form", id="ID of the Form"}) 
{ //form here
}
Ammar
  • 1,068
  • 2
  • 13
  • 20
  • 1
    Instead of "Target-ViewName where you want to post the page" I think you mean "Target action method to which you want to post the data". – Sachin Kainth Sep 24 '13 at 14:32
-4

Taken from this answer: How to pass in ID with Html.BeginForm()?

Can you not just do:

Html.BeginForm(new {@id="Id", @name="Id"}); 

It can pay to search SO for answers as I've found many things I want to ask have already been encountered.

Community
  • 1
  • 1
Paul Hadfield
  • 6,088
  • 2
  • 35
  • 56
  • you're adding route values though. not html attributes – BritishDeveloper Sep 10 '10 at 09:14
  • I see your answer where you're passing in nulls, I did think you could just use the defaults for the named parameters and pass in a list of additional attributes to append to the output HTML – Paul Hadfield Sep 10 '10 at 09:29
  • i tried your solution before but it generate code like this "
    "
    – user426306 Sep 10 '10 at 09:49
  • Sorry about that, I did think that was the way it worked - obviously not. In that case, this might be a good example of when to provide your own HTML extension method, or just revert back to good old HTML. – Paul Hadfield Sep 10 '10 at 10:14