Let’s now look at a more complete scenario involving our
model, where we use a controller class to implement the functionality necessary
to publish a list of upcoming dinners, and enable users to add new ones:
We’ll implement this functionality by
right-clicking on the “Controllers” folder and choose the “Add->Controller”
menu command. We’ll name our new controller “HomeController”.
We’ll then add three “action methods” within
it that work with the NerdDinners model we created earlier using EF
“Code-First”:
The “Index” action method above retrieves and
renders a list of upcoming dinners.
The “Create” action methods allow users to add
new dinners. The first “Create” method above handles the “HTTP GET”
scenario when a user visits the /Home/Create URL, and send back a “New Dinner”
form to fill out. The second “Create” method handles the “HTTP POST”
scenario associated with the form – and handles saving the dinner in the
database. If there are any validation issues it redisplays the form back
to the user with appropriate error messages.
Adding Views for our Controllers
Our next step will be to add two “View
templates” to our project – one for “Index” and one for “Create”.
We’ll add the “Index” view to our project by
moving our cursor within the Index action method of our controller, and then
right-click and choose the “Add View” menu command. This will bring up
the “Add View” dialog. We’ll specify that we want to create a
strongly-typed view, and that we are passing in a IEnumerable list of “Dinner”
model objects to it:
When we click “Add”, Visual Studio will create
a /Views/Home/Index.aspx file. Let’s then add the following code to it –
which generates a <ul> list of Dinners, and renders a hyperlink that
links to our create action:
We’ll then add the “Create” view to our
project by moving our cursor within the Create action method of our controller,
and then right-click and choose the “Add View” menu command. Within the
“Add View” dialog we’ll specify that we want to create a strongly-typed view,
and that we are passing it a Dinner object. We’ll also indicate that we
want to “scaffold” using a “Create” template:
When we click “Add”, Visual Studio will create
a /Views/Home/Create.aspx file with some scaffold-generated content within it
that outputs an HTML <form> for a “Dinner” object. We’ll tweak it
slightly and remove the input element for the DinnerID property. Our
final view template content will look like this:
We have now implemented all of the code we need to write
within our Controller and Views to implement the Dinner listing and Dinner
creation functionality within our web application.