Creating Your First ASP.NET MVC 6 Application Using c# From Scratch.

Note: For this post, you’ll need the basic understanding of how MVC works.

MVC 6 the Integrated Framework

Web Pages + MVC + Web API = MVC 6



     Web Pages


HTML Helpers






Model Binding
Dependency Resolver

 ASP.NET 5 MVC, Web API and Web Pages are combined into one framework to form MVC 6.

In previous versions of ASP.NET MVC, MVC controllers were different from Web API controllers. An MVC controller used the System.Web.MVC.Controller base class and a Web API controller used the System.Web.Http.ApiController base class. In MVC 6, there is only one Controller base class for both MVC and Web API controllers that is the Microsoft.AspNet.Mvc.Controller class.

Let’s Start!

Okay, launch Visual Studio 2015 and select File > New > Project. In the New Project dialog select Templates > Visual C# > ASP.NET Web Application. See the following image for a clear view:

Creating Your First ASP.NET MVC 6 Application Using c# From Scratch

Figure: ASP .NET Web Application.

Name your project whatever you like and then click OK. For the simplicity of this demo, we named the project “MVC6Demo”. You should then be able to see the “New ASP.NET Project” dialog as shown in the following image:

Creating Your First ASP.NET MVC 6 Application Using c# From Scratch.

Image: Name of the Web Application.

The new ASP.NET Project dialog for ASP.NET 4.6 templates allows you to select the type of project you want to create. Configure any combination of technologies such as WebForms, MVC or Web API, configure a unit test project, configure the authentication option and a new option is available to host your website in the Azure cloud. Adding to that, it also provides templates for ASP.NET 5.

But the goal here is to build an MVC 6 application from scratch, so select the ASP.NET 5 Empty template from the dialog above. Then click OK to let Visual Studio generate the necessary files and templates needed.

You should be able to see something as in the following image:

Creating Your First ASP.NET MVC 6 Application Using c# From Scratch

Image: Welcome Window.

You will notice that the new project structure is totally different compared to the previous versions of ASP.NET. The project now includes these files:

  • src folder: contains all projects that contain source code that make up your application.
  • global.json: this is where you put solution-level settings and allows you to do project-to-project references.
  • wwwroot: is a folder in which all your static files will be placed. These are the assets that the web app will serve directly to the clients, including HTML, CSS, Image and JavaScript files.
  • project.json: contains project settings.
  • startup.cs: this is where you put your startup and configuration code.

 Setting up the MVC folder structures

To maintain the MVC pattern, let’s create the “Models”, “Views” and “Controllers” folders just like in the following image:

Creating Your First ASP.NET MVC 6 Application Using c# From Scratch.

Image: Solution Explorer.

Introducing the project.json file

The “project.json” file serves as the new project file (.csproj/.vbproj). This is where we put all the dependencies that our application requires.

The interesting thing about the project.json file is that it provides intellisense for the available packages when you add or edit dependencies. All packages that you’ve added from this file will be automatically pulled from NuGet. Correspondingly when you remove packages it automatically removes them from your project reference. A really great addition!

Right now, there’s no MVC in our app since we are creating an empty ASP.NET 5 template. To add the MVC dependency to our project just modify the project.json file by adding “Microsoft.AspNet.MVC” under the dependencies section. Your project.json should look like this:

  1. “webroot”: “wwwroot”,
  2. “version”: “1.0.0-*”,
  3. “dependencies”:
  4. {
  5. “Microsoft.AspNet.Server.IIS”: “1.0.0-beta3”,
  6. “Microsoft.AspNet.Mvc”: “6.0.0-beta3”
  7. },
  8. “frameworks”:
  9. {
  10. “aspnet50”: {},
  11. “aspnetcore50”: {}
  12. },

Now save the project.json file to restore NuGet packages. The MVC framework should now be added to our application as shown in the following image:

Creating Your First ASP.NET MVC 6 Application Using c# From Scratch.

Image: References.

Configure the application pipeline

Since we are done with adding the MVC dependency, our next step is to add the MVC framework in the pipeline. To achieve that, open up Startup.cs file and add the following code under the Configure method:

  1. publicvoid Configure(IApplicationBuilder app)
  2. {
  3. UseMvc(m = >
  4. {
  5. MapRoute(
  6. name: “default”,
  7. template: “{controller}/{action}/{id?}”,
  8. defaults: new
  9. {
  10. controller = “Home”, action = “Index”
  11. });
  12. });
  13. }

The code above is almost similar to the old MVC for defining routes, except that we are now using the UseMvc method to setup the routes.

Now we need to hook up the pieces of MVC by adding the dependencies that MVC 6 requires. So your ConfigureServices method should now look like this:

  1. publicvoid ConfigureServices(IServiceCollection services)
  2. AddMvc();
  3. }

The AddMvc() is an extension method that does all the magic for us. It basically adds the dependencies needed for MVC 6.

Adding Models

Now let’s add a simple model that we can test. For this example I’m creating the following class under the “Models” folder:

  1. usingSystem;
  2. namespaceModels
  3. {
  4. public class FavoriteBook
  5. {
  6. public int ID
  7. {
  8. get;
  9. set;
  10. }
  11. publicstring Name
  12. {
  13. get;
  14. set;
  15. }
  16. publicstring Type
  17. {
  18. get;
  19. set;
  20. }
  21. }
  22. }

And then add the following class that manages the “FavoriteBook” class:

  1. usingCollections.Generic;
  2. usingLinq;
  3. namespaceModels
  4. {
  5. public class BookManager
  6. {
  7. readonly List <FavoriteBook > _books = new List <FavoriteBook > ()
  8. {
  9. newFavoriteBook
  10. {
  11. ID = 1, Name = “The Princess and the Pea”, Type = “Story”
  12. },
  13. newFavoriteBook
  14. {
  15. ID = 2, Name = “The Girl on the Train”, Type = “Story”
  16. },
  17. newFavoriteBook
  18. {
  19. ID = 3, Name = “Paradise Lost”, Type = “Poetry”
  20. },
  21. newFavoriteBook
  22. {
  23. ID = 4, Name = “The Man with Night Sweats”, Type = “Poetry”
  24. },
  25. newFavoriteBook
  26. {
  27. ID = 5, Name = “The Main Enemy”, Type = “Intelligence”
  28. },
  29. newFavoriteBook
  30. {
  31. ID = 6, Name = “The Jungle Book”, Type = “Story”
  32. },
  33. newFavoriteBook
  34. {
  35. ID = 7, Name = “Primal Leadership”, Type = “Intelligence”
  36. },
  37. };
  38. publicIEnumerable <FavoriteBook > GetAll
  39. {
  40. get
  41. {
  42. return_books;
  43. }
  44. }
  45. publicList <FavoriteBook> GetBooksByType(string type)
  46. {
  47. return_books.Where(b = > b.Type.ToLower().Equals(type.ToLower())).ToList();
  48. }
  49. }
  50. }

The “BookManager” class contains a readonly property that contains a list of books. For simplicity, the data is obviously static. In a real world scenario you may need to get the data from a storage such as database or any files that stores your data. It also contains a GetAll property that returns all the books and finally a GetBooksByType() method that returns a list of books based on the book type.


Adding a Controller

Just right click on the “Controllers” folder and then select Add > New Item. In the dialog select MVC Controller Class as shown in the following image:


Image: Add Controller.

Then just go ahead and click Add to generate the controller class for you. Here’s the HomeController class:

  1. usingAspNet.Mvc;
  2. usingModels;
  3. namespaceControllers
  4. {
  5. public class HomeController: Controller
  6. {
  7. public IActionResult Index()
  8. {
  9. BookManager bm = new BookManager();
  10. var books= bm.GetAll;
  11. returnView(books);
  12. }
  13. }
  14. }

In the above code snippet, IActionResult() method returns the list of books that comes from the model.

Adding a View

To add views just do the same thing as what we did to add the controller. But before that we must add a “Home” folder under the “Views” folder to follow the MVC convention. Right-click on the “Home” folder and select Add > New Item > MVC View Page:

Creating Your First ASP.NET MVC 6 Application Using c# From Scratch.

Image: Add View.

Now click add to generate the file. Now there’s no magic in creating our view since we didn’t use any scaffolding template. Instead we need to setup the view manually. Here’s what my view looks like:

  1. @model IEnumerable
  2. <MVC6Demo.Models.FavoriteBook>
  3. <h3>My Favorite Books</h3>
  4. <ul>
  5. @foreach (var b in Model)
  6. {
  7. <li>@string.Format(“{0} {1}”, b.Name, b.Type)</li>
  8. }

The view above is a strongly-typed view. By including a @model statement at the top of the view template file, you can specify the type of object that view expects. In this case it uses the IEnumerable<MVC6Demo.Models.FavoriteBook>


Image: Output

That is the output when running the app in the browser.

That’s it! Now let’s try to look at other new cool features in MVC 6.

Introducing Inject

ASP.NET MVC 6 has a few new directives that we can use in our application. Here we’ll have a look at how to use @inject. The @inject directive allows you to inject some method calls from a class or service directly into your view. To see that in action I’ve created a new class called “BookStats” under the Models folder. Here’s the simple class that exposes some async methods:

  1. usingLinq;
  2. usingThreading.Tasks;
  3. namespaceModels
  4. {
  5. public class BookStats
  6. {
  7. private BookManager _manager = new BookManager();
  8. public async Task <int> GetBookCount()
  9. {
  10. returnawait Task.FromResult(_manager.GetAll.Count());
  11. }
  12. publicasync Task <int> GetBookCountByType(string type)
  13. {
  14. returnawait Task.FromResult(_manager.GetBooksByType(type).Count);
  15. }
  16. }
  17. }

The class above initializes a new instance of BookManager. It also contains two main async methods. GetBookCount() returns the total count of the books and GetBookCountByType() returns the number of books based on a given type. Now inject the class into the View:

  1. @model IEnumerable
  2. <MVC6Demo.Models. FavoriteBook>
  3. @inject MVC6Demo.Models.BookStats Stats
  4. <h3>My Favorite Books</h3>
  5. <ul>
  6. @foreach (var b in Model)
  7. {
  8. <li>@string.Format(“{0} {1}”, b.Name, b.Type)</li>
  9. }
  10. </ul>
  11. <div>
  12. <span>Number of Story: @await Stats. GetBookCountByType(“story”)</span>
  13. <br/>
  14. <span>Number of Poetry: @await Stats. GetBookCountByType (“poetry”)</span>
  15. <br/>
  16. <span>Number of Intelligence: @await Stats.GetBookCountByType(“intelligence”)</span>
  17. <br/>
  18. <span>Total Heroes: @await Stats.GetBookCount()</span>
  19. </div>

In order to make it work we need to configure the AddTransient() method by adding the BookStats model into it. So the Configure method would now look like this:

  1. publicvoid ConfigureServices(IServiceCollection services)
  2. {
  3. AddMvc();
  4. AddTransient < MVC6Demo.Models.BookStats> ();
  5. }

Running the app will display the following output:

Creating Your First ASP.NET MVC 6 Application Using c# From Scratch.

Image: Output.

Introducing View Components

Another cool feature in MVC 6 is the “View Components”. If you remember, in previous versions of ASP.NET MVC, the Html.Action() helper is typically used to invoke a sub-controller. A sub-controller may display stuff like tag clouds, dynamic links, side bars or whatever. ASP.NET MVC 6 introduced the new View Component to replace widgets that use Html.Action().

View Components also support fully async allowing you to make a view component asynchronous.

Now let’s try to create a very simple view component and let’s see how they are used in MVC. To start, create a new folder at the root of your application and name it “ViewComponents”. Within that folder create a new class and name it “BookListViewComponent” and copy the following code:

  1. usingAspNet.Mvc;
  2. usingThreading.Tasks;
  3. usingModels;
  4. usingCollections.Generic;
  5. namespaceViewComponents
  6. {
  7. public class BookListViewComponent: ViewComponent
  8. {
  9. public async Task < IViewComponentResult > InvokeAsync(string type)
  10. {
  11. var books= await GetBooksAsync(type);
  12. returnView(books);
  13. }
  14. privateTask < IEnumerable <FavoriteBook>> GetBooksAsync(string type)
  15. {
  16. returnFromResult(GetBooks(type));
  17. }
  18. privateIEnumerable <FavoriteBook> GetBooks(string type)
  19. {
  20. BookManager bm = newBookManager();
  21. returnGetBooksByType(type);
  22. }
  23. }
  24. }

Just like the controllers, view components also follow a convention for naming classes. This means we can create a view component by adding the suffix “ViewComponent” to your class. Adding to that ViewComponent must be public, non-nested and non-abstract classes.

Now let’s add the view for the View Component that we just have created. Keep in mind that View Component follows a convention too when referencing views. So the first thing to do is to create a new folder within the Home folder. The folder name must be “Components”. Now since we followed the convention in our example, the next thing to do is to create another new folder within the Components folder, this time the folder name must match your class name minus the “ViewComponents” suffix. In this case name the folder BookList”. Finally add a new view within the BookList folder and name it “Default” since we didn’t specify the view to render in our InvokeAsync code. Your project structure should now look like the following:

Creating Your First ASP.NET MVC 6 Application Using c# From Scratch.

Image: Solution Explorer.

In your Default.cshtml file, add the following markup for your View Component’s view:

  1. @model IEnumerable<MVC6Demo.Models.FavoriteBook>
  2. <h3>Story Books</h3>
  3. <ul>
  4. @foreach (var s in Model)
  5. {
  6. <li>@s.Name</li>
  7. }
  8. </ul>

And here’s how we call the View Component from the main view (Index.cshmtl):

Running the page will display the following output:

Creating Your First ASP.NET MVC 6 Application Using c# From Scratch.

Image: Final Output.


That’s it. Happy programming………………….

Warning: Use of undefined constant php - assumed 'php' (this will throw an Error in a future version of PHP) in /home/u3l8rkb6k3a2/domains/ on line 29

8 thoughts on “Creating Your First ASP.NET MVC 6 Application Using c# From Scratch.

Leave a Reply

Your email address will not be published. Required fields are marked *