Injecting a service into a view in MVC 6
Asp.net MVC 6 supports injecting service to view using a class.
Example :- When country combo box value get changed , region com
Only restriction is that class should be
- Public
- Non-nested
- Non-Abstract
1. Create a Asp.Net Project in Visual Studio 2015
2. Create a folder name services and add a service class.
- using System;
- using System.Threading.Tasks;
- namespace ViewInjection.Services
- {
- public class EmployeeService
- {
- public async Task<int> GetEmployeesOnLeaveCount()
- {
- return await Task.FromResult(5);
- }
- public async Task<int> GetEmployeesOnSiteCount()
- {
- return await Task.FromResult(
- 10);
- }
- public async Task<int> GetEmployeesOnWorkCount()
- {
- return await Task.FromResult(97);
- }
- }
- }
2. Create a View to show Employee statistics and add the inject statement to the top of the file.
- @inject ViewInjection.Services.EmployeeService EmployeeService
- @{
- ViewBag.Title = "Employee Page";
- }
3. Call the service as below
- @inject ViewInjection.Services.EmployeeService EmployeeService
- @{
- ViewBag.Title = "Employee Page";
- }
- <h3>Employee Stats</h3>
- <ul>
- <li>On Leave: @await EmployeeService.GetEmployeesOnLeaveCount()</li>
- <li>On Site:@await EmployeeService.GetEmployeesOnSiteCount()</li>
- <li>On Work:@await EmployeeService.GetEmployeesOnWorkCount()</li>
- </ul>
4. Register the EmployeeService
class in the Startup.cs file.
- public void ConfigureServices(IServiceCollection services)
- {
- // Add EF services to the services container.
- services.AddEntityFramework(Configuration)
- .AddSqlServer()
- .AddDbContext<ApplicationDbContext>();
- // Add Identity services to the services container.
- services.AddDefaultIdentity<ApplicationDbContext, ApplicationUser, IdentityRole>(Configuration);
- // Add MVC services to the services container.
- services.AddMvc();
- services.AddTransient<ViewInjection.Services.EmployeeService>();
- }
5. Add a action method in HomeController.cs
- public IActionResult EmployeeStaticstics()
- {
- return View();
- }
6.Run your code you will see the output as below.
Happy Coding !!
Why when we remove the roles authorize does not work automatically, because I need to log out and then a login for work? The problem is that the roles are stored in the cookie. I have to find some solution to update the cookie. When do I remove a roles directly in the database the cookie is outdated. I think I have update the cookie to each User request. The example I'm using is on github https://github.com/aspnet/Musi...
ReplyDelete