views:

237

answers:

3

What does Html.BeginForm() do and is it necessary?

Sometimes I forget to put it on a form that takes user input but things still seem to work. What am I missing out on when I don't have it?

A: 

It's not necessary at all. It's simply a helper which handles setting up the form tags. It's a good idea to use it though. My intuition says they will enhance this helper to handle things like XSS attacks etc. that you currently have to deal with using the AntiForgeryToken helper and associated attribute.

Nissan Fan
+1  A: 

BeginForm() simply writes out the form tag using the parameters supplied to it. If you don't have a form you won't or if you're doing all of your page interaction with AJAX you might not need it. If you only have links on the page, then a form is unnecessary. Unless you use AJAX, though, you can't do POST requests to your controller actions without using it to inject your form tag or injecting your form tag manually.

tvanfosson
+1  A: 

Essentially, it outputs a

<form>

tag into the HTML output. The form tag is required if your page POSTs (i.e. a button is pressed to submit the form), so that the browser knows where to submit the form. The reason it might be working right now for you, is because you might not have any buttons - jsut links (I dont know what your application is, so just guessing here).

In short: if you want to be able to submit a form to an action, yes, that tag is required. If you do it all through links, you dont need a form tag, and thus BeginForm is not really needed.

HTH.

P.S. read Scott Guthrie's blog posts on ASP.NET MVC, they really help a lot to get you started.

AASoft
Not really sure how this answers the real question.
Nissan Fan
I can write out my own form and action tags and they will work fine. The whole point of this method is to abstract out the functionality and make it adaptable.
Nissan Fan