-->

Friday, September 7, 2018

How to use Tabs in ASP.NET CORE



I want to show Components in a tabs , so first of all create few components. In this project we have three components,

First View Component

 public class AllViewComponent : ViewComponent
    {

        private readonly UserManager<ApplicationUser> _userManager;

        public AllViewComponent(UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }
        public async Task<IViewComponentResult> InvokeAsync()
        {
            List<StudentViewModel> allUsers = new List<StudentViewModel>();
            var items = await _userManager.Users.ToListAsync();
            foreach (var item in items)
            {
                allUsers.Add(new StudentViewModel {Id=item.Id, EnrollmentNo = item.EnrollmentNo, FatherName = item.FatherName, Name = item.Name, Age = item.Age, Birthdate = item.Birthdate, Address = item.Address, Gender = item.Gender, Email = item.Email });
            }

            return View(allUsers);
        }
    }

Second View Component

 public class StudentsViewComponent : ViewComponent
    {

        private readonly UserManager<ApplicationUser> _userManager;

        public StudentsViewComponent(UserManager<ApplicationUser> userManager)
        {
           _userManager = userManager;
        }
        public async Task<IViewComponentResult> InvokeAsync()
        {
            List<StudentViewModel> students = new List<StudentViewModel>();
            var items = await _userManager.GetUsersInRoleAsync("Student");
            foreach (var item in items)
            {
                students.Add(new StudentViewModel {EnrollmentNo=item.EnrollmentNo,FatherName=item.FatherName, Name = item.Name, Age = item.Age, Birthdate = item.Birthdate, Address = item.Address, Gender = item.Gender, Email = item.Email });
            }

            return View(students);
        }
    }

Third View Component

public class TeacherViewComponent : ViewComponent
    {
        private readonly UserManager<ApplicationUser> _userManager;
     
        public TeacherViewComponent(UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }
        public async Task<IViewComponentResult> InvokeAsync()
        {
            List<TeacherViewModel> teachers = new List<TeacherViewModel>();
            var items = await _userManager.GetUsersInRoleAsync("Teacher");
            foreach (var item in items)
            {
                teachers.Add(new TeacherViewModel {FatherName=item.FatherName, Name = item.Name, Age = item.Age, Birthdate = item.Birthdate, Address = item.Address, Gender = item.Gender, Email = item.Email });
            }
     
            return View(teachers);
        }

       
    }


Under Shred Folder Create tree structured directory like this 
/Shared/Components/All
/Shared/Components/Teacher
/Shared/Components/Students

Under All Directory , you can create a view which default name is "Default"

@model IEnumerable<StudentManagementSystem.ViewModels.StudentViewModel>

@{
    ViewData["Title"] = "Default";
}



<table class="table">
    <thead>
        <tr>
                <th>
                    @Html.DisplayNameFor(model => model.EnrollmentNo)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Age)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Birthdate)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Gender)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Address)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.FatherName)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Email)
                </th>
               
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.EnrollmentNo)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Age)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Birthdate)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Gender)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Address)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.FatherName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Email)
            </td>
           
            <td>
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

Similarly you can create view to other two views.

Now, If you want to implements tabs view then create a ViewModel Class for tabs 

namespace StudentManagementSystem.ViewModels
{
    public class UsersTabViewModel
    {
        public Tab ActiveTab { get; set; }
    }

    public enum Tab
    {
        All,
        Teachers,
        Students
    }
}

Now, You can use it in cshtml file like this 

@model StudentManagementSystem.ViewModels.UsersTabViewModel
@{
    ViewData["Title"] = "Index";
}

<h2>Users Table</h2>
<ul class="nav nav-tabs">
    <li role="presentation" class="@(Model.ActiveTab == StudentManagementSystem.ViewModels.Tab.All ? "active" : string.Empty )"><a asp-route-tabname="All" asp-action="SwitchToTabs">All</a></li>
    <li role="presentation" class="@(Model.ActiveTab == StudentManagementSystem.ViewModels.Tab.Teachers ? "active" : string.Empty )"><a asp-route-tabname="Teachers" asp-action="SwitchToTabs">Teachers</a></li>
    <li role="presentation" class="@(Model.ActiveTab == StudentManagementSystem.ViewModels.Tab.Students ? "active" : string.Empty )"><a asp-route-tabname="Students" asp-action="SwitchToTabs">Students</a></li>
</ul>
@switch (Model.ActiveTab)
{
    case StudentManagementSystem.ViewModels.Tab.All:
        @await Component.InvokeAsync("All");
        break;
    case StudentManagementSystem.ViewModels.Tab.Teachers:
        @await Component.InvokeAsync("Teacher");
        break;
    case StudentManagementSystem.ViewModels.Tab.Students:
        @await Component.InvokeAsync("Students");
        break;
    default:
        break;
}


Now, The controller section for each route value are

 public IActionResult Index(UsersTabViewModel vm)
        {
            if (vm == null)
            {
                vm = new UsersTabViewModel
                {
                    ActiveTab = Tab.All
                };
            }
            return View(vm);
        }
        public IActionResult SwitchToTabs(string tabname)
        {
            var vm = new UsersTabViewModel();
            switch (tabname)
            {
                case "All":
                    vm.ActiveTab = Tab.All;
                    break;
                case "Teachers":
                    vm.ActiveTab = Tab.Teachers;
                    break;
                case "Students":
                    vm.ActiveTab = Tab.Students;
                    break;
                default:
                    vm.ActiveTab = Tab.All;
                    break;
            }
            return RedirectToAction(nameof(AdminController.Index), vm);
        }



Thursday, June 28, 2018

Highlight Table Row based on some Condition in ASP.NET Core

Model Class

public class Products
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Price { get; set; }
    }

Controller Code 

public IActionResult Index()
        {
            List<Products> p1 = new List<Products>();
            p1.Add(new Products { Id = 1, Name = "Samsung", Price = 50 });
            p1.Add(new Products { Id = 2, Name = "Samsung1", Price = 50 });
            p1.Add(new Products { Id = 3, Name = "Samsung2", Price = 150 });
            p1.Add(new Products { Id = 4, Name = "Samsung3", Price = 150 });
            p1.Add(new Products { Id = 5, Name = "Samsung4", Price = 550 });
            p1.Add(new Products { Id = 6, Name = "Samsung5", Price = 550 });
            return View(p1);
        }

View Section

@model IEnumerable<TestingApplication.Models.Products>

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Id)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Price)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            @if (item.Price > 0 && item.Price < 100)
            {
                <tr class="label-success">
                    <td>

                        @Html.DisplayFor(modelItem => item.Id)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Price)
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                        @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                        @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
                    </td>
                </tr>
            }
            @if (item.Price > 100 && item.Price < 200)
            {
                <tr class="label-warning">
                    <td>

                        @Html.DisplayFor(modelItem => item.Id)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Price)
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                        @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                        @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
                    </td>
                </tr>
            }
            @if (item.Price > 150 && item.Price < 600)
            {
                <tr class="label-primary">
                    <td>

                        @Html.DisplayFor(modelItem => item.Id)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Price)
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                        @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                        @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
                    </td>
                </tr>
            }
        }
    </tbody>
</table>



Tuesday, February 6, 2018

Step By Step Guide to use WebAPI in ASP.NET CORE WebApplication

If you have to completed your WebAPI then must to know , how to use it in web application.  Now , you can see , how to use WebAPI in WebApplication.

WEBAPI Project
Step-1 :   Create Model first
public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Step-2 :  Create Data Context Class

public class Context : DbContext
    {
        public Context(DbContextOptions<Context> options) : base(options)
        {

        }
        public DbSet<Student> Students { get; set; }

    }

Step-3 :  Add Connection String into your Application Setting File

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-6550C064-027F-4939-822B-5B4620D08657;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Step-4 :  Add Connection String in Startup file

  services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


Step-5 Do Migration 
Step-6 :  Create Controller 

namespace WebApiTestApplication.Controllers
{
    [Route("api/[controller]")]
    public class StudentController : Controller
    {
        private Context _context;
        public StudentController(Context context)
        {
            _context = context;
        }
        [HttpGet]
        public List<Student> Get()
        {
            return _context.Students.ToList();
        }

        public IActionResult Index()
        {
            return View();
        }
    }}

Step- 7: Add new project Web Application in the same solution
Step-8 : Add Helper Class  also add View Model class

namespace WebApplication1.Helper
{
    public class StudentAPI
    {
        public HttpClient Initial()
        {
            var Client = new HttpClient();
            Client.BaseAddress = new Uri("http://localhost:56562/");
            return Client;
        }
    }

}

If you Know what is "56562" then must to watch the video

And the model class

namespace WebApiTestApplication.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Step-9 :  Add A controller

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        StudentAPI _api = new StudentAPI();

        public async Task<IActionResult> Index()
        {
            List<Student> student = new List<Student>();
            HttpClient client = _api.Initial();
            HttpResponseMessage res = await client.GetAsync("api/Student");
            if (res.IsSuccessStatusCode)
            {
                var result = res.Content.ReadAsStringAsync().Result;
                student = JsonConvert.DeserializeObject<List<Student>>(result);
            }
         
            return View(student);
        }


    }
}

Step-10  : Generate View as list type 

@model IEnumerable<WebApiTestApplication.Models.Student>

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Id)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
            </td>
        </tr>
}
    </tbody>
</table>



© Copyright 2013 Computer Programming | All Right Reserved