We already discussed about the Controllers and Routers in ASP.Net MVC 3. In this article, we will look little deeper into Controllers and Razor Views.
Controllers and Routers in ASP.NET MVC 3
Controller with CRUD operations
Let us define our Model first. For our sample, we will define a Sample Model class
publicclassSampleModel
{
publicint Id { get; set; }
publicstring FirstName { get; set; }
publicstring LastName { get; set; }
publicint Age { get; set; }
}
Now let us add a new Controller. Right Click on the Controllers folder and select Add-> Controller.
This will open the Add Controller Window. Specify the
Controller name as SampleController and select the Scaffolding options.
For our sample, select the Template as ‘Controller with read/write actions and views, using Entity Framework’. This will add actions for all operations like edit, list, etc.
Select our SampleModel under Model class. Select New DataContext option in Data context class and specify the name for the new data context.
Select the Views as Razor.
Note: MVC supports two types of view engines; one is the Web form view engine and another is the Razor View engine. Web form view engine works with aspx/ascx files and razor view engine work with cshtml file. We will discuss more about Razor views latter.
This will create the SampleController, which supports all the CRUD operations. It also generates the Sample folder and views under the Views folder.
Let us run the application and verify the Sample pages.
Your Sample controller page
Note that the page is constructed with data from your Model class. Also, it allows us to add data to the SampleModel. Click on Create New link.
This will open the Create action view and allows us to enter data.
Now, it will display the entered data with edit, delete and details options.
Click on Details will display the detailed view of the record.
Now, close the application and re-run the same. You may be surprised to see the data entered earlier displayed in the web application.
Now the question is where the data is saving? Answer is CodeFirst approach introduced as part of Entity Framework. For more details on CodeFirst Approach, please refer my article EntityFramework-CodeFirst Approach.
Open the server explorer and connect to the SqlExpress. Notice that, we have a new database in sqlexpress with the name SampleApp.Context.SampleAppContext.
Connect to the new database and observe that we have a new table with SampleModels with the data, which we entered in the web application UI.
Filed under: ASP.Net, Entity Framework, MVC Tagged: ASP.Net, ASP.Net MVC 3, EntityFramework, MVC