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 |
|
MVC |
Controllers |
Web API |
||
Actions | ||||||
Filters | ||||||
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:
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:
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:
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:
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:
- “webroot”: “wwwroot”,
- “version”: “1.0.0-*”,
- “dependencies”:
- {
- “Microsoft.AspNet.Server.IIS”: “1.0.0-beta3”,
- “Microsoft.AspNet.Mvc”: “6.0.0-beta3”
- },
- “frameworks”:
- {
- “aspnet50”: {},
- “aspnetcore50”: {}
- },
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:
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:
- publicvoid Configure(IApplicationBuilder app)
- {
- UseMvc(m = >
- {
- MapRoute(
- name: “default”,
- template: “{controller}/{action}/{id?}”,
- defaults: new
- {
- controller = “Home”, action = “Index”
- });
- });
- }
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:
- publicvoid ConfigureServices(IServiceCollection services)
{ - AddMvc();
- }
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:
- usingSystem;
- namespaceModels
- {
- public class FavoriteBook
- {
- public int ID
- {
- get;
- set;
- }
- publicstring Name
- {
- get;
- set;
- }
- publicstring Type
- {
- get;
- set;
- }
- }
- }
And then add the following class that manages the “FavoriteBook” class:
- usingCollections.Generic;
- usingLinq;
- namespaceModels
- {
- public class BookManager
- {
- readonly List <FavoriteBook > _books = new List <FavoriteBook > ()
- {
- newFavoriteBook
- {
- ID = 1, Name = “The Princess and the Pea”, Type = “Story”
- },
- newFavoriteBook
- {
- ID = 2, Name = “The Girl on the Train”, Type = “Story”
- },
- newFavoriteBook
- {
- ID = 3, Name = “Paradise Lost”, Type = “Poetry”
- },
- newFavoriteBook
- {
- ID = 4, Name = “The Man with Night Sweats”, Type = “Poetry”
- },
- newFavoriteBook
- {
- ID = 5, Name = “The Main Enemy”, Type = “Intelligence”
- },
- newFavoriteBook
- {
- ID = 6, Name = “The Jungle Book”, Type = “Story”
- },
- newFavoriteBook
- {
- ID = 7, Name = “Primal Leadership”, Type = “Intelligence”
- },
- };
- publicIEnumerable <FavoriteBook > GetAll
- {
- get
- {
- return_books;
- }
- }
- publicList <FavoriteBook> GetBooksByType(string type)
- {
- return_books.Where(b = > b.Type.ToLower().Equals(type.ToLower())).ToList();
- }
- }
- }
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:
- usingAspNet.Mvc;
- usingModels;
- namespaceControllers
- {
- public class HomeController: Controller
- {
- public IActionResult Index()
- {
- BookManager bm = new BookManager();
- var books= bm.GetAll;
- returnView(books);
- }
- }
- }
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:
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:
- @model IEnumerable
- <MVC6Demo.Models.FavoriteBook>
- <h3>My Favorite Books</h3>
- <ul>
- @foreach (var b in Model)
- {
- <li>@string.Format(“{0} {1}”, b.Name, b.Type)</li>
- }
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>
Output
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:
- usingLinq;
- usingThreading.Tasks;
- namespaceModels
- {
- public class BookStats
- {
- private BookManager _manager = new BookManager();
- public async Task <int> GetBookCount()
- {
- returnawait Task.FromResult(_manager.GetAll.Count());
- }
- publicasync Task <int> GetBookCountByType(string type)
- {
- returnawait Task.FromResult(_manager.GetBooksByType(type).Count);
- }
- }
- }
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:
- @model IEnumerable
- <MVC6Demo.Models. FavoriteBook>
- @inject MVC6Demo.Models.BookStats Stats
- <h3>My Favorite Books</h3>
- <ul>
- @foreach (var b in Model)
- {
- <li>@string.Format(“{0} {1}”, b.Name, b.Type)</li>
- }
- </ul>
- <div>
- <span>Number of Story: @await Stats. GetBookCountByType(“story”)</span>
- <br/>
- <span>Number of Poetry: @await Stats. GetBookCountByType (“poetry”)</span>
- <br/>
- <span>Number of Intelligence: @await Stats.GetBookCountByType(“intelligence”)</span>
- <br/>
- <span>Total Heroes: @await Stats.GetBookCount()</span>
- </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:
- publicvoid ConfigureServices(IServiceCollection services)
- {
- AddMvc();
- AddTransient < MVC6Demo.Models.BookStats> ();
- }
Running the app will display the following output:
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:
- usingAspNet.Mvc;
- usingThreading.Tasks;
- usingModels;
- usingCollections.Generic;
- namespaceViewComponents
- {
- public class BookListViewComponent: ViewComponent
- {
- public async Task < IViewComponentResult > InvokeAsync(string type)
- {
- var books= await GetBooksAsync(type);
- returnView(books);
- }
- privateTask < IEnumerable <FavoriteBook>> GetBooksAsync(string type)
- {
- returnFromResult(GetBooks(type));
- }
- privateIEnumerable <FavoriteBook> GetBooks(string type)
- {
- BookManager bm = newBookManager();
- returnGetBooksByType(type);
- }
- }
- }
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.
Notes
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:
Image: Solution Explorer.
In your Default.cshtml file, add the following markup for your View Component’s view:
- @model IEnumerable<MVC6Demo.Models.FavoriteBook>
- <h3>Story Books</h3>
- <ul>
- @foreach (var s in Model)
- {
- <li>@s.Name</li>
- }
- </ul>
And here’s how we call the View Component from the main view (Index.cshmtl):
Running the page will display the following output:
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/codemen.com/html/wp-content/themes/cm/template-parts/content-single.php on line 29
Whenever you search towards something captivating, analysis this out
http://studenthousingtroy.com/2020/08/07/earn-no-cost-income-through-over-the-internet-casino-corporation-games/
щедрый веб ресурс https://casino-top3.fun
When you search towards something enthralling, watchdog this in negligence
https://uniform-wiki.win/index.php/15_Tips_About_quality_enscapsulation_garcinia_cambogia_review_From_Industry_Experts
Whenever you search on something intriguing, trial this in neglect
https://online-wiki.win/index.php/So_You've_Bought_keto_fuel_review_…_Now_What%3F
When you search to something engaging, check this discernible
https://cristianscrv614.page.tl/A-best_keto_supplement-.-com-Success-Story-You-h-ll-Never-Believe.htm
Whenever you are searching to something irresistible, in control this in fault
http://www.mayogiardelli.com.ar/sin-categoria/todas-las-transgress-city-on-line-casinos-procuring-perfectly-made-to-roll/
When you search someone is concerned something intriguing, hamper this in neglect
http://martiscafe.com/todas-las-sinfulness-city-limits-betting-houses-attaining-well-willing-for-you-to-roll/
When you search towards something intriguing, in control this discernible
https://mike-wiki.win/index.php/17_Reasons_Why_You_Should_Ignore_keto_amino_acids