Now let's Add EmployeeController class to "Controllers" folder. To do this1. Right click on "Controllers" folder > Add > Controller2. Use EmployeeController as the name3. Click "Add"

We want to use "Employee" model class in EmployeeController. So copy and paste the following "using" statement in "EmployeeController.cs"using MVCDemo.Models;

By default an Index() Action method is created in EmployeeController. Change the name of the function to Details(). Create an instance of Employee class. For now we will hard code Employee data in this class. In a later video session, we will discuss about retrieving employee information from the database table tblEmployee. At this point EmployeeController should look as shown below.publicActionResult Details(){Employee employee = new Employee() { EmployeeId = 101, Name = "John", Gender = "Male", City = "London" };return View();}

Now, we need to pass the employee model object that we constructed in EmployeeController to a view, so the view can generate the HTML and send it to the requested client. To do this we first need to add a view. To add a view1. Right click on Details() action method and select "Add View" from the context menu2. Seta)View Name = Detailsb)View Engine = Razorc)Select "Create strongly typed view" check boxd)From the "Model class" dropdownlist, select "Employee (MVCDemo.Models)" Note: If Employee class is not visible in the dropdownlist, please build your project and then try adding the view again.3. Finally click "Add"

At this point, Details.cshtml should be added to "Employee" folder. Please note that "Employee" folder is automatically created and added to "Views" folder.

Copy and paste the following code in Details.cshtml file.@model MVCDemo.Models.Employee

At this point if you run the project, and if you navigate to the following URL, you get a runtime error stating - Object reference not set to an instance of an object.http://localhost/MVCDemo/Employee/Details

To fix this error, pass "Employee" object to the view. The "return" statement in Details() action method need to be modified as shown below.return View(employee);

That's it. Run the application and navigate to http://localhost/MVCDemo/Employee/Details. We should get the output as expected.

10 comments:

Great videos! I'm receiving an error when trying to view data from my database though that says a primary key has not been defined. However, I do have my Category_ID column set as a primary key in the database. How do I handle this exception. I'm very new to MVC and coding in general so any help is much appreciated!

I Am getting tgis error The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'MVCModel.Controllers.EmployeeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.Parameter name: parameters