Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using HTML forms in ASP.NET MVC?

Tags:

asp.net-mvc

It seems like everything I look up on this subject has either changed since the release or is wildly different from eachother.

I just want to create a simple form in my view.

Should I be using the Html.BeginForm()/TextBox()/EndForm() methods or should I be using a plain-jane HTML form? Which is preferred?

This is what I have so far:

<%=Html.BeginForm("Create", "Product", FormMethod.Post); %>  
    <%=Html.TextBox("productTextBox", "Enter a shoe name"); %>  
    <input type="submit" name="createButton" value="Create Me!" />    
<%=Html.EndForm(); %>  

What is the "correct" way to create a simple form with a button and textbox in ASP.NET MVC and allow me to submit the data in the form to the /Product/Create action?

How do I then access the form data from within that method? Some people seem to use a "FormCollection" and others just do a Request.Form method. Which way should I use?

Can someone enlighten me?

like image 508
Mithrax Avatar asked Nov 21 '25 00:11

Mithrax


1 Answers

The Form helpers are the recommended way because it allows you to provide a controller, action and other route data and the URL is auto-generated based on your routes (in Global.asax). The advantage is, if you decide to change your routes, you don't have to update every URL in your site.

The only reason I'd use an actual "<form>" tag was if I needed extra control over the markup that I couldn't get from Html.Form (I can't think of an example right now). Even if you choose to do that, you should use the "Url.Action" helper to get a URL from routing data. For example:

<form action="<%= Url.Action("Create") %>">

As for your second question, I'd suggest using the Model Binder. Check out ScottGu's Blog for some details on this.

like image 103
Andrew Stanton-Nurse Avatar answered Nov 22 '25 17:11

Andrew Stanton-Nurse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!