The details action method
Let us implement the details action method
Preparing the index view
First let us examine the last row of current code in index.cshtml file and understand how the details link work
The scaffolding just created some boiler plate code previously, we will now replace it quit specific code as shown below, since we now have information about the model and its properties - in this case movie and Id:
Replacing last row of index.cshtml file
Note:
we are using asp helper tags in place of razor expressions since it is easier to work with
the asp-action specifies which action method should be invoked on the controller
similarly, the asp-route-id appends the item Id as a route parameter as expected by our routing template
notice how we are using @ symbol do you use actual property - our primary key of movie model, Id in this case
Preparing the controller
Let us first take a look at the existing code for the details action method of the movies controller
Again, this is just a generic code we need to modify this in order to show the details of the selected movie in a Details
form. Also note than this action method is invoked on an HTTP Get call, since we need to get the details from the server!
Modify the Details action as shown
Note:
NotFound() is a method inherited from the base controller - using these we don't have to remember status code for HTTP errors
Single() is a method which we can call on any collection using LINQ, to fetch a single object which matches the expression provided
if the movie is found we pass it to the view so that it can render the HTML based on the template we will create called the
Details
view shortly
Let us tidy the code
Add a constructor to the controller and instantiate _context inside it,
Also remove the fake context object creation from Index() method as well, since the constructor is doing it for us now
Ad
Preparing the Details view
Using scaffolding again, let us add a razor view (inside Views\Movies
folder) with the template as shown:
Click on Add
Here is the generated code for Details.cshtml file
This is markup code based on the model we selected, it is creating a bunch of labels and text boxes in which we can display the details of the selected movie object.
Run the application now
Run the application now and access the movie list using the below URL
Hover the mouse on the Details hyperlink of second movie and you will see the URL that will be in invoked on clicking it, as prompted by the browser at its bottom section:
Click on Details link on any movie, and you will see the Details view!
Last updated