1. Back To Blog

Differentiate ASP.NET MVC 5 and ASP.Net Core 2.0 MVC.

Contents :-

ASP Core 2.0 MVC Tutorial

 Introduction to ASP CORE 2.0 MVC

.Net Core:

✓ The new .Net Core is an open source Cross Platform version of .Net Framework.

✓ It is also a Subset of the full .Net Framework.

✓ Interestingly it only supports a single app model that being Console Applications.

ASP.Net Core:

✓It is the biggest redesign of the ASP.Net since ASP.Net 1.0

✓ ASP.Net Core is no longer based on System.Web.dll

✓ The ASP.Net Core application can run on either .Net Core or the Full .Net Framework

✓ ASP.Net Core applications can be hosted on Windows, Linux and MacOS.

✓ It is Open source and Community supported.

✓ These Applications can be hosted on IIS or can be hosted on nginx or other non-windows servers on top of Kestrel Web Server.

Requirements for this Demonstration:

➤ Visual Studio 2017 Community, Professional or Enterprise with .Net Core Cross-platform development package installed.

➤ You can download Visual Studio 2017 from the following link: https://www.visualstudio.com/downloads/ using .Net Core Application with Visual Studio 2017 is a better combination than with Earlier Versions of Visual Studios.

➤ Supported versions of Windows Operating Systems: Windows 7 SP1 or higher.

➤ Supported versions of Mac Operating Systems: MacOS 10.12 "Sierra"

➤ Supported versions of Linux Operating Systems: Red Hat Enterprise Linux 7, CentOS 7,Oracle Linux 7, Fedora 25, Fedora 26,Debian 8.7 or later versions, Ubuntu 17.04, Ubuntu 16.04, Ubuntu 14.04,Linux Mint 18, Linux Mint 17,openSUSE 42.2 or later versions, SUSE Enterprise Linux (SLES) 12 SP2 or later versions

➤ SQL Server 2012 or Higher for Windows Operating systems.

➤ Download and Install the .Net Core SDK for your respective Operating Systems from the Following link:- https://www.microsoft.com/net/download/core

Steps for creating a simple ASP.Net Core 2.0 application:

  1. Start a new Project in Visual Studio 2017  


     
  2. Let's Click on Empty and Look at the Structure and Working of a Basic ASP CORE.Net Application before delving in MVC
     
                       

                       

                       

                       

                       

                       

                       

                       

                      There you have created an ASP.Net Core project in just two steps now let's look at the folder structure.

                       

                             

                           

                           

                           

                           

                           

                          As we can see in the above folder structure there are no Global.asax and Web.Config files in MVC Core and if you have already experience with ASP.Net Core 1.0 on Visual Studio 15 you might find the Project.json file absent.

                          Also there is an addition of a few new files namely Startup.cs and Program.cs plus a folder called wwwroot.

                          As we have said earlier ASP.Net Core apps are built on a single app model i.e. Console application hence the presence of Program.cs file.

                          While Startup.cs represents the entry point into our application.

                          There are a few Fundamentals Concepts which we must understand before continuing.

                          Forward and they are listed as follows:

                          • Application Startup: Startup class is the entry point to our application and is required by all applications.
                            Startup Class must contain two methods Configure and ConfigureServices which get started when our application is started.
                            The Configure method is used to define how an ASP.Net Core Application responds to every single HTTPS requests.
                            The ConfigureServices is used to manage services that are used in our application. 
                          • Middleware: Middleware are software component which control how our application responds to Http requests.
                          • Working with Static Files: HTML, CSS, Images, and JavaScript etc. are the Static files that are stored in wwwroot folder of our application.
                            Static file calls are not enabled by default so we must use "app.UseStaticFiles();"
                            Middleware in Configure method. But before that we sure to install the nugget dependencies.

                             


                             

                          • Globalization and localization: Globalization and localization both are part of Intertionalization.
                            Globalization is the process of creating apps that support different cultures and environment.
                            Localization is the process of adapting a Globalized app to particular culture for a Targeted locale. 
                          • Error Handling: ASP.Net Core does not have an inbuilt exception handler hence we a get Server 500 error if we try to run it on a browser.
                            To overcome this problem ASP.Net Core uses a middleware for handling exception handling in Configure method.
                          public void Configure(IApplicationBuilder app, IHostingEnvironment env)
                                  
                                      if (env.IsDevelopment())
                                      
                                          app.UseDeveloperExceptionPage();
                                      }
                                  }
                          

                          In Program.cs we have static void main() which starts our application just like a console application.

                          Static void Main contains a call for "BuildWebHost(args).Run();" which creates Host for handling http requests and a call to Startup Class.

                          Also we can configure our Dependencies in the new csproj file dynamically without closing our Visual Studio IDE.

                           

                           

                           

                           

                           

                           

                           

                          What is MVC?

                          MVC stands for Model-View-Controller which is an architectural design pattern.

                          MVC separates the application body into three different parts Models, Views and Controllers for Ensuring separation of concerns.

                          The following diagram represents a MVC relationship:

                           

                           

                           

                           

                           

                           

                           

                           

                           

                           

                           

                           

                          Model:- Model is a class that describes data that we are working with as well as contain the business logic.

                          View:- It is the HTML template in which we display our User interface.

                          Controller:- Controllers are classes which handle interaction with user, data handling with models and decide which view to be rendered.

                          ASP.Net MVC 5 vs ASP.Net Core 2.0 MVC

                          Comparing the Project structure of MVC 5 and MVC Core 2.0 we can clearly see the absences of Global.asax and Web.Config

                           

                           

                           

                           

                          There is no Content, Script and Font folders as all these contain Static files which are now housed under a single folder in MVC Core 2.0 called wwwroot.

                          appsettings.json and configuration files which can be customized to any format such as XML, Json etc.

                          In ASP.Net Core 2.0 router configuration does not have a separate file like in MVC 5 it's incorporated in Startup.cs itself.

                          Dependency Injection is Inbuilt in ASP.Net Core Applications so we can just create a service and use it with dependency injection unlike in MVC 5 in which we have to separate DI containers.

                          In ASP.Net Core 2.0 MVC we have IActionResult instead of ActionResult as return type in controller.

                          Steps to Setup a MVC Core 2.0 Project:

                          1. Create a new project with the following configuration




















                          2. Next Choose Web Application(Model-View-Controller) also ensure ASP.Net Core 2.0 is Selected.



                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                  Our Project Structure should look like this in our created MVC project

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                  Initial run of our application should look something like this in the browser

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   
                                  Performing a Simple CRUD Operation in ASP CORE 2.0 MVC

                                  First we need to create a simple table in database to perform CRUD operation on

                                   

                                   

                                   
                                  Here is script for a simple table and database creation

                                  Create database Student
                                  GO
                                  USE [Student]
                                  GO
                                  SET ANSI_NULLS ON
                                  GO
                                  SET QUOTED_IDENTIFIER ON
                                  GO
                                  CREATE TABLE [dbo].[Student_info](
                                   [Id] [int] IDENTITY(1,1) NOT NULL,
                                   [Name] [varchar](50) NULL,
                                   [Course] [varchar](100) NULL,
                                   [Age] [int] NULL
                                  ) ON [PRIMARY]
                                  GO
                                  SET IDENTITY_INSERT [dbo].[Student_info] ON 
                                  GO
                                  INSERT [dbo].[Student_info] ([Id], [Name], [Course], [Age]) VALUES (1, N'Umed', N'Java', 24)
                                  GO
                                  SET IDENTITY_INSERT [dbo].[Student_info] OFF
                                  GO
                                  

                                  Next Step is to add Entity Framework core to the project so we need to go to
                                  Tools > NuGet Package manger and select Console option as follows

                                   

                                   

                                   And Run the following command in the given sequence:

                                  Install-Package Microsoft.EntityFrameworkCore.SqlServer

                                  Next entity framework core tools to create a model from the database

                                  Install-Package Microsoft.EntityFrameworkCore.Tools

                                  .NET Core scaffolding tools to create new controllers and views

                                  Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

                                  Now we need to create a connection to database so in Visual Studio go views and click on Server Explorer.

                                  Right Click on Data Connections and add a new connection.

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                  After creating the new connection check its properties and copy the connection string to notepad

                                  We can either manually create a DbContext and Model Class or generate it using a command from our existing database.

                                  Here is the command to generate the Class and DbContext automatically.

                                  Scaffold-DbContext "Your connection string that you have copied to notepad goes here" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

                                  Your Generated or Handwritten Student Class should look something like this

                                  using System;
                                  using System.Collections.Generic;
                                  namespace MVC_CORE.Models
                                  
                                      public partial class StudentInfo
                                      
                                          public int Id  get; set; }//Student Id and primary key
                                          public string Name  get; set; }//Name of the Student
                                          public string Course  get; set; }//Course Name
                                          public int? Age  get; set;}//Age of the Student
                                      }
                                  }
                                  

                                  And Your DbContext should resemble this code

                                  using System;
                                  using Microsoft.EntityFrameworkCore;
                                  using Microsoft.EntityFrameworkCore.Metadata;
                                  namespace MVC_CORE.Models
                                  
                                      public partial class StudentContext : DbContext
                                      
                                          public virtual DbSet StudentInfo  get; set; }
                                          public StudentContext(DbContextOptions options)
                                      : base(options)
                                           }
                                          protected override void OnModelCreating(ModelBuilder modelBuilder)
                                          
                                              modelBuilder.Entity(entity =>
                                              
                                                  entity.ToTable("Student_info");
                                                  entity.Property(e => e.Course)
                                                      .HasMaxLength(100)
                                                      .IsUnicode(false);
                                                  entity.Property(e => e.Name)
                                                      .HasMaxLength(50)
                                                      .IsUnicode(false);
                                              });
                                          }
                                      }
                                  }
                                  

                                  In ASP.Net Core 2.0 Configurations are generally used in Startup.cs

                                  Hence we must remove the inline configuration generated in DbContext class and add it to Startup.cs.

                                  To follow convention remove

                                  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

                                  And add

                                  public StudentContext(DbContextOptions< StudentContext > options)
                                      : base(options)
                                   }

                                  To use dependency injection which will passed in this constructor for allowing access of configuration to this context.

                                  In Startup.cs we need to add the following namespaces

                                  using Student.Models;
                                  using Microsoft.EntityFrameworkCore;
                                  

                                  Now we can use AddDbContext() method and register it as a service

                                  After rewriting ConfigureServices in Startup.cs

                                  public void ConfigureServices(IServiceCollection services)
                                  
                                  services.AddMvc();
                                  var connection = @"Your Connection string";
                                  services.AddDbContext(options => options.UseSqlServer(connection));
                                          }
                                  

                                  Next Step is to add a new controller in the controller's folder and select MVC Controller with views, using Entity Framework

                                  The Configure the controller next by select our Student DbContext and Student Model as shown by the below images

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                  Navigate to Views\Shared\_Layout.cshtml and the following line add Create to the Menu in the landing page in the navbar div.

                                  <li><a asp-area="" asp-controller="StudentInfoes" asp-action="Create">Create Student</a></li>

                                  Now run the application without debugging (Ctrl + F5)

                                  To Navigate to the Create page add "Your Controller Name without the Controller keyword"/Create

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                  ENTERING DATA TO THE CREATE PAGE WILL TAKE YOU TO THE PAGE WHICH IS AN INDEX AND HAS OPTIONS FOR UPDATE AND DELETE THE DATA.

                                   

                                   

                                   

                                   

                                   

                                   

                                   

                                   
                                  Concluding this tutorial for ASP.Net Core 2.0 MVC we can see the majority of the MVC structure remains the same but there are some big changes Entity framework and ASP.Net as a whole.

                                  Shiv Prasad Koirala

                                  Visit us @ www.questpond.com or call us at 022-66752917... read more

                                  We are on Social