We’ll begin by adding a simple “Person” class to a new
ASP.NET MVC 2 project that looks like below:
It has four properties (implemented using C#’s automatic property support, which VB in VS 2010 now
supports too – woot!).
We’ll then add a “FriendsController” controller class to our
project that exposes two “Create” action methods. The first action method
is called when an HTTP-GET request comes for the /Friends/Create URL. It
will display a blank form for entering person data. The second action
method is called when an HTTP-POST request comes for the /Friends/Create
URL. It maps the posted form input to a Person object, verifies that no
binding errors occurred, and if it is valid will eventually save it to a
database (we’ll implement the DB work later in this tutorial). If the
posted form input is invalid, the action method redisplays the form with
errors:
After we’ve implemented our controller, we can right-click
within one of its action methods and choose the “Add View” command within
Visual Studio – which will bring up the “Add View” dialog. We’ll choose
to scaffold a “Create” view that is passed a Person object:
Visual Studio will then generate a scaffolded Create.aspx
view file for us under the \Views\Friends\ directory of our project.
Notice below how it takes advantage of the new strongly-typed HTML helpers in ASP.NET MVC 2 (enabling
better intellisense and compile time checking support):
And now when we run the application and hit
the /Friends/Create URL we’ll get a blank form that we can enter data into:
Because we have not implemented any validation within the
application, though, nothing prevents us from entering bogus input within the
form and posting it to the server.