mvc Archives - Tech Insights Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Tue, 10 Jan 2023 17:38:23 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 mvc Archives - Tech Insights 32 32 230003556 How to Create Dynamic Menu in Asp.Net Core MVC C# https://reactconf.org/how-to-create-dynamic-menu-in-asp-net-core-mvc-c/ https://reactconf.org/how-to-create-dynamic-menu-in-asp-net-core-mvc-c/#comments Tue, 10 Jan 2023 17:38:23 +0000 https://labpys.com/?p=643 In this article, we will learn How to Create a Dynamic Menu in Asp.Net Core MVC C#. In the previous article, we discussed https://labpys.com/how-to-generate-qr-code-using-asp-net-core-c/. Prerequisites Create an ASP.NET Core MVC …

The post How to Create Dynamic Menu in Asp.Net Core MVC C# appeared first on Tech Insights.

]]>
In this article, we will learn How to Create a Dynamic Menu in Asp.Net Core MVC C#. In the previous article, we discussed https://labpys.com/how-to-generate-qr-code-using-asp-net-core-c/.

Dynamic Menu in Asp.Net Core MVC C#

Prerequisites

  • Download and install .Net Core 6.0 SDK from here
  • Download and Install Microsoft Visual Studio 2022 from here
  • Sql-Server

Create an ASP.NET Core MVC Project

Open visual studio, Go to File menu and click on New and select Project. Then new project window, select ASP.NET Core Web Application (Model-View-Controller) template.

Dynamic Menu in Asp.Net Core MVC C#

Enter  project name and click create.

Dynamic Menu in Asp.Net Core MVC C#

Install NuGet Packages

  • Microsoft Entity Framework Core Sql Server.
  • Microsoft Entity Framework Core Tools

Configure appsettings.json

There are two connection string one is SQL Server and another one is excel .

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "sqlconnection": "Server=(local)\\MSSQL;Database=InventoryDB;Trusted_Connection=True;MultipleActiveResultSets=true",   
    
  },
  "AllowedHosts": "*"
}

Create Model

Create Model class and DbContext Class.

//MenuMast.cs

using DocumentFormat.OpenXml.Presentation;
using System.ComponentModel.DataAnnotations;

namespace Asp.netcore_Tutorials.Models
{
    public class MenuMast
    {
        public MenuMast()
        {
            SubMenuMast = new HashSet<SubMenuMast>();
        }

        [Key]
        public int MenuCode { get; set; }

        [Required]
        [StringLength(250)]
        public string MenuName { get; set; }

        [StringLength(10)]
        public string DesignCodeTime { get; set; }

        public int? MenuSortOrder { get; set; }

        public virtual ICollection<SubMenuMast> SubMenuMast { get; set; }

    }
}

SubMenuMast.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Asp.netcore_Tutorials.Models
{
    public class SubMenuMast
    {
        
        [Key]
        public int SubMenuCode { get; set; }

        public int ModuleCode { get; set; }
     
        [Required]
        [StringLength(150)]
        public string SubMenuName { get; set; }

        [StringLength(150)]
        public string TableName { get; set; }

        public bool HideFlag { get; set; }

        public int? SubMenuSortOrder { get; set; }

        public int MenuCode { get; set; }
        [ForeignKey(nameof(MenuCode))]
        public virtual MenuMast MenuMasts { get; set; } 
    }
}

MenuDbcontext.cs

using Microsoft.EntityFrameworkCore;

namespace Asp.netcore_Tutorials.Models
{
    public class MenuDbcontext : DbContext 
    {
        public MenuDbcontext(DbContextOptions<MenuDbcontext> option):base(option)
        {

        }

        public virtual DbSet<MenuMast> MenuMasts { get; set; }
        public virtual DbSet<SubMenuMast> SubMenuMasts { get; set; }
   
    }
}

Create Interface and Concrete Class

Interface IMenuNavigation.cs

using Asp.netcore_Tutorials.Models;

namespace Asp.netcore_Tutorials.Repository
{
    public interface IMenuNavigation
    {
        Task<IEnumerable<SubMenuMast>> MenuList();
        Task<IEnumerable<MenuMast>> MenuMastList();             
    }
}

Concrete Class MenuNavigation.cs

using Asp.netcore_Tutorials.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections;

namespace Asp.netcore_Tutorials.Repository
{
    public class MenuNavigation : IMenuNavigation
    {
        private readonly MenuDbcontext _menuDbcontext;

        public MenuNavigation(MenuDbcontext menuDbcontext)
        {
            _menuDbcontext = menuDbcontext;
        }
        public async Task<IEnumerable<SubMenuMast>> MenuList()
        {
            return await _menuDbcontext.SubMenuMasts.Include(m=>m.MenuMasts).ToListAsync();
        }
        public async Task<IEnumerable<MenuMast>> MenuMastList()
        {
             return await _menuDbcontext.MenuMasts.Include(m=>m.SubMenuMast).ToListAsync();
        }
    }
}

Configure Program.cs

using Asp.netcore_Tutorials.Models;
using Asp.netcore_Tutorials.Repository;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Configuration;
using Microsoft.AspNetCore.Session;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

 
builder.Services.AddDbContext<MenuDbcontext>(conn => conn.UseSqlServer(builder.Configuration.GetConnectionString("sqlconnection")));
 
builder.Services.AddScoped<IMenuNavigation, MenuNavigation>();

builder.Services.AddSession();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseSession();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Migration

Add-Migration 'Initial-Create'
Update-Database

Create View Model

menuViewModel.cs

using Asp.netcore_Tutorials.Models;

namespace Asp.netcore_Tutorials.ViewModel
{
    public class menuViewModel
    {
      //  public  ICollection<SubMenuMast> menuListViewModel { get; set; }
        public IEnumerable<MenuMast> MenuList { get; set; }
    }
}

Create Controller

MenuController.cs

using Asp.netcore_Tutorials.Repository;
using Microsoft.AspNetCore.Mvc;
using Asp.netcore_Tutorials.ViewModel;
using Microsoft.AspNetCore.Mvc.Rendering;
using Asp.netcore_Tutorials.Models;

namespace Asp.netcore_Tutorials.Controllers
{
    public class MenuController : Controller
    {
        private readonly IMenuNavigation _menuList;

        public MenuController(IMenuNavigation menuList)
        {
            _menuList = menuList;
        }

        public IActionResult Index()
        {
            menuViewModel menuListViewModel = new menuViewModel();     
            menuListViewModel.MenuList =  _menuList.MenuMastList().Result.ToList();
            return View(menuListViewModel);
        }
    }
}

Customize View

index.cs

 
@model Asp.netcore_Tutorials.ViewModel.menuViewModel;
 
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <title></title>

        <!-- Bootstrap CSS CDN -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <!-- Our Custom CSS -->
      
        <!-- Scrollbar Custom CSS -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">

         
       <link href="~/css/style.css" rel="stylesheet" />

    </head>
    <body>
        <div class="wrapper">
            <!-- Sidebar Holder -->
            <nav id="sidebar">
                <div class="sidebar-header">
                    <h3>Dynamic Menu</h3> 
                </div>

                <ul class="list-unstyled components">
                 @foreach (var menu in Model.MenuList)
                 {
                  <li class="active">
                        <a href="#@menu.MenuName" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">@menu.MenuName</a>
                    <ul class="collapse list-unstyled" id="@menu.MenuName">
                       @if (@menu.SubMenuMast.Count > 0)
                            {
                                @foreach (var item in menu.SubMenuMast)
                                {
                                    <li><a href="@item.SubMenuName">@item.SubMenuName</a></li>
                                }; 
                            };                     
                    
                    </ul>
                    </li>
                   };
                  </ul>              
            </nav>

            <!-- Page Content Holder -->
            <div id="content">

                <nav class="navbar navbar-default">
                    <div class="container-fluid">

                        <div class="navbar-header">
                            <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">
                                <i class="glyphicon glyphicon-align-left"></i>
                                <span>Toggle Sidebar</span>
                            </button>
                        </div>

                        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                            <ul class="nav navbar-nav navbar-right">
                                <li><a href="#">Page</a></li>
                            </ul>
                        </div>
                    </div>
                </nav>

            
            </div>
        </div>

         <!-- jQuery CDN -->
    <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    <!-- Bootstrap Js CDN -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!-- jQuery Custom Scroller CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>
 
 
    <script type="text/javascript">
        $(document).ready(function () {

            $('#sidebarCollapse').on('click', function () {
                $('#sidebar').toggleClass('active');
            });

        });
    </script>
    </body>
</html>

 

The post How to Create Dynamic Menu in Asp.Net Core MVC C# appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-create-dynamic-menu-in-asp-net-core-mvc-c/feed/ 2 643
How to create Login Page using Asp.net Core MVC C# With Database https://reactconf.org/how-to-create-login-page-using-asp-net-core-mvc-c-with-database/ https://reactconf.org/how-to-create-login-page-using-asp-net-core-mvc-c-with-database/#comments Fri, 09 Dec 2022 17:51:03 +0000 https://labpys.com/?p=481 Authentication is mandatory for security in any type of application. One of the fundamental requirements for an application is a login page, which is why many application development processes begin …

The post How to create Login Page using Asp.net Core MVC C# With Database appeared first on Tech Insights.

]]>
Authentication is mandatory for security in any type of application. One of the fundamental requirements for an application is a login page, which is why many application development processes begin with implementing an authentication module. In this article, we’ll learn how to create login page using asp.net core MVC C# With Database.

Pre-requisite

  • NET Core SDK from here
  • Visual Studio or Visual Studio Code from here
  • SQL Server database from here

Create an ASP.NET Core MVC Project

Go to the File menu and click on New and select Project. In the new project window, select ASP.NET Core Web App(Model-View-Controller).

Document

More Related Article

Then set the project location and project name.

Install NuGet package

Once the new project is created install NuGet Packages for that right click on Solution and select Manage NuGet Packages for the solution  

  • Microsoft Entity Framework Core SQL Server
  • Microsoft Entity Framework Core Tools

Configure appsettings.json

The connection string “connectionstr” is saved in appSettings.json , you can change it as per your need

"ConnectionStrings": {
    "connectionstr": "Server=(local)\\MSSQL;Database=Login_Auth;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

Create Model

Creating a model is an essential step in developing an ASP.NET Core application. A model is a representation of the data that our application will use and manipulate. By creating a model, we define the structure of the data and its relationships with other models. This allows us to easily work with data in our application and perform CRUD (Create, Read, Update, Delete) operations on it

using System.ComponentModel.DataAnnotations;
namespace Auth_Login.Models
{
    public class UserLogin
    {
        [Key]
        public int id { get; set; }

        [Required(ErrorMessage ="Please Enter Username")]
        [Display(Name = "Please Enter Username")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Please Enter Password")]
        [Display(Name = "Please Enter Password")]
        public string passcode { get; set; }
        public int isActive { get; set; }

    }
}

Create Dbcontext Class

DbContext is class in Entity Framework API. It is a bridge between your domain class and the database. DbContext is the class that is responsible for interacting with the database. As per Microsoft  “A DbContext instance represents a combination of the Unit Of Work and Repository pattern such that it can be used to query from a database”

using Microsoft.EntityFrameworkCore;

namespace Auth_Login.Models
{
    public class LoginDbcontext : DbContext 
    {
        public LoginDbcontext(DbContextOptions<LoginDbcontext> options)
            :base(options)
        {

        }

        public DbSet<UserLogin> UserLogin { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.Entity<UserLogin>(entity=> {
                entity.HasKey(k=>k.id);
                });
        }
    }
}

Create a Repository and interface

Now create a repository folder, in this folder create two class, Create Interface  ILogin.cs file and AuthenticateLogin.cs

ILogin.cs

using System.Collections.Generic;
using System.Threading.Tasks;
using Auth_Login.Models;

namespace Auth_Login.Repository
{
    public interface ILogin
    {
        Task<IEnumerable<UserLogin>> getuser();
        Task<UserLogin> AuthenticateUser(string username,string passcode);
    }
}

AuthenticateLogin.cs

using Auth_Login.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Auth_Login.Repository
{
    public class AuthenticateLogin : ILogin
    {
        private readonly LoginDbcontext _context;

        public AuthenticateLogin(LoginDbcontext context)
        {
            _context = context; 
        }
        public async Task<UserLogin> AuthenticateUser(string username, string passcode)
        {
           var succeeded = await _context.UserLogin.FirstOrDefaultAsync(authUser => authUser.UserName == username && authUser.passcode == passcode);
           return succeeded;
        }

        public async Task<IEnumerable<UserLogin>> getuser()
        {
             return await _context.UserLogin.ToListAsync(); 
        }
    }
}

Configure Startup Class

Update startup class with database connection and as well as inject services.
Startup.cs

using Microsoft.EntityFrameworkCore;
using Auth_Login.Models;
using Auth_Login.Repository;
public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<LoginDbcontext>(conn => conn.UseSqlServer(Configuration.GetConnectionString("connectionstr")));
            services.AddScoped<ILogin, AuthenticateLogin>();

            services.AddControllersWithViews();
        }

Migration

Then create a Database through Migration. Go to Tools>NuGet Package Manager>Package Manager Console then execute the following commands.

Add-Migration “Initial Create”

Update-Database

Create Controller

Now create IActionResult Index Method with the parameter

using Auth_Login.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Auth_Login.Repository;

namespace Auth_Login.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogin _loginUser;

        public HomeController(ILogin loguser)
        {
            _loginUser = loguser;   
        }

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

        [HttpPost]
        public IActionResult Index(string username,string passcode)
        {
            var issuccess = _loginUser.AuthenticateUser(username, passcode);


            if (issuccess.Result != null)
            {
                ViewBag.username = string.Format("Successfully logged-in", username);

                TempData["username"] = "Ahmed";
                return RedirectToAction("Index", "Layout"); 
            }
            else {
                ViewBag.username = string.Format("Login Failed ", username);
                return View();
            } 
        } 
       
    }
}

Customize View Index

Go to Views>Home>Index cshtml file update.

<html>
<head>

 <link rel="stylesheet" href="~/css/Style.css" />
</head>

<body>
<div class="login">
  <h1>Login to Web App</h1>

  <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index" >
    <p><input type="text" name="username" value="" placeholder="Username or Email" required></p>     
    <p><input type="password" name="passcode" value="" placeholder="Password" required></p>     
    <p class="remember_me">
      <label>
        <input type="checkbox" name="remember_me" id="remember_me">
        Remember me on this computer
      </label>
    </p>
    <p class="submit"><input type="submit" name="commit" value="Login"></p>
    <hr/>
    @ViewBag.username
  </form>
</div> 
</body>
</html>

Create style.css  file in  wwwroot>css>style.css

body {
    font: 13px/20px "Lucida Grande", Tahoma, Verdana, sans-serif;
    color: #404040;
    background: #0ca3d2;
}

.login {
    position: relative;
    margin: 30px auto;
    padding: 20px 20px 20px;
    margin-top : 200px;
    width: 310px;
    background: white;
    border-radius: 3px;
    -webkit-box-shadow: 0 0 200px rgba(255, 255, 255, 0.5), 0 1px 2px rgba(0, 0, 0, 0.3);
    box-shadow: 0 0 200px rgba(255, 255, 255, 0.5), 0 1px 2px rgba(0, 0, 0, 0.3);
}
 

    .login:before {
        content: '';
        position: absolute;
        top: -8px;
        right: -8px;
        bottom: -8px;
        left: -8px;
        z-index: -1;
        background: rgba(0, 0, 0, 0.08);
        border-radius: 4px;
    }

    .login h1 {
        margin: -20px -20px 21px;
        line-height: 40px;
        font-size: 15px;
        font-weight: bold;
        color: #555;
        text-align: center;
        text-shadow: 0 1px white;
        background: #f3f3f3;
        border-bottom: 1px solid #cfcfcf;
        border-radius: 3px 3px 0 0;
        background-image: -webkit-linear-gradient(top, whiteffd, #eef2f5);
        background-image: -moz-linear-gradient(top, whiteffd, #eef2f5);
        background-image: -o-linear-gradient(top, whiteffd, #eef2f5);
        background-image: linear-gradient(to bottom, whiteffd, #eef2f5);
        -webkit-box-shadow: 0 1px whitesmoke;
        box-shadow: 0 1px whitesmoke;
    }

    .login p {
        margin: 20px 0 0;
    }

        .login p:first-child {
            margin-top: 0;
        }

    .login input[type=text], .login input[type=password] {
        width: 278px;
    }

    .login p.remember_me {
        float: left;
        line-height: 31px;
    }

        .login p.remember_me label {
            font-size: 12px;
            color: #777;
            cursor: pointer;
        }

        .login p.remember_me input {
            position: relative;
            bottom: 1px;
            margin-right: 4px;
            vertical-align: middle;
        }

    .login p.submit {
        text-align: right;
    }

.login-help {
    margin: 20px 0;
    font-size: 11px;
    color: white;
    text-align: center;
    text-shadow: 0 1px #2a85a1;
}

    .login-help a {
        color: #cce7fa;
        text-decoration: none;
    }

        .login-help a:hover {
            text-decoration: underline;
        }

:-moz-placeholder {
    color: #c9c9c9 !important;
    font-size: 13px;
}

::-webkit-input-placeholder {
    color: #ccc;
    font-size: 13px;
}

input {
    font-family: 'Lucida Grande', Tahoma, Verdana, sans-serif;
    font-size: 14px;
}

    input[type=text], input[type=password] {
        margin: 5px;
        padding: 0 10px;
        width: 200px;
        height: 34px;
        color: #404040;
        background: white;
        border: 1px solid;
        border-color: #c4c4c4 #d1d1d1 #d4d4d4;
        border-radius: 2px;
        outline: 5px solid #eff4f7;
        -moz-outline-radius: 3px;
        -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.12);
        box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.12);
    }

        input[type=text]:focus, input[type=password]:focus {
            border-color: #7dc9e2;
            outline-color: #dceefc;
            outline-offset: 0;
        }

    input[type=submit] {
        padding: 0 18px;
        height: 29px;
        font-size: 12px;
        font-weight: bold;
        color: #527881;
        text-shadow: 0 1px #e3f1f1;
        background: #cde5ef;
        border: 1px solid;
        border-color: #b4ccce #b3c0c8 #9eb9c2;
        border-radius: 16px;
        outline: 0;
        -webkit-box-sizing: content-box;
        -moz-box-sizing: content-box;
        box-sizing: content-box;
        background-image: -webkit-linear-gradient(top, #edf5f8, #cde5ef);
        background-image: -moz-linear-gradient(top, #edf5f8, #cde5ef);
        background-image: -o-linear-gradient(top, #edf5f8, #cde5ef);
        background-image: linear-gradient(to bottom, #edf5f8, #cde5ef);
        -webkit-box-shadow: inset 0 1px white, 0 1px 2px rgba(0, 0, 0, 0.15);
        box-shadow: inset 0 1px white, 0 1px 2px rgba(0, 0, 0, 0.15);
    }

        input[type=submit]:active {
            background: #cde5ef;
            border-color: #9eb9c2 #b3c0c8 #b4ccce;
            -webkit-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
            box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
        }

.lt-ie9 input[type=text], .lt-ie9 input[type=password] {
    line-height: 34px;
}

 Then build the project and Execute it.

The post How to create Login Page using Asp.net Core MVC C# With Database appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-create-login-page-using-asp-net-core-mvc-c-with-database/feed/ 5 481