asp.net core mvc Archives - Tech Insights Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Fri, 10 Nov 2023 11:03:11 +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 asp.net core mvc Archives - Tech Insights 32 32 230003556 How to download multiple files in ASP.NET Core MVC https://reactconf.org/how-to-download-multiple-files-in-asp-net-core-mvc/ https://reactconf.org/how-to-download-multiple-files-in-asp-net-core-mvc/#respond Fri, 10 Nov 2023 11:03:11 +0000 https://labpys.com/?p=2121 This article explains how to download multiple files using ASP.NET Core MVC. First, create a table to store file information, such as filename and source path. Here is the following …

The post How to download multiple files in ASP.NET Core MVC appeared first on Tech Insights.

]]>
This article explains how to download multiple files using ASP.NET Core MVC. First, create a table to store file information, such as filename and source path.

Here is the following step-by-step guide to download multiple files in ASP.NET Core MVC:

Create an Asp.NET Core MVC Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project.

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web Application” from the list of available templates.
  • Click the Next button.
  • Then configure a new project, and specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Create a Model

namespace WebApplication_Download_Files.Models
{
    public class FileAssets
    {
        public Guid Id { get; set; }
        public string Filename { get; set; } = null;
        public string FileUrls { get; set; } = null;

        public FileAssets()
        {
            Id = Guid.NewGuid();
        }
    }
}

Configure Database Connection

Open the Program.cs file and add the following code snippet.

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.SqlServer;
using Microsoft.Extensions.Configuration;
using WebApplication_Download_Files.Models;


var builder = WebApplication.CreateBuilder(args);

//Connection string
// "connectionstr": //"Server=localhost;Database=inventoryDb;Encrypt=False;Trusted_Connection=True;"

builder.Services.AddDbContext<AppDbContext>(opt=> opt.UseSqlServer(builder.Configuration.GetConnectionString("connectionstr")));
// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

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

app.Run();

Migration

Run the following command in the package manager console.

add-migration 'Init-create'
update-database

Create Controller

Open the HomeController.cs file. Create a new method named “downloadAll”

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
using System.Text;
using WebApplication_Download_Files.Models;
using Microsoft.AspNetCore.Hosting;
using System.IO.Compression;

namespace WebApplication_Download_Files.Controllers
{
    public class HomeController : Controller
    {
        
        private readonly AppDbContext _context;
        private readonly IWebHostEnvironment _env;

        public HomeController(AppDbContext context, IWebHostEnvironment env)
        {
           
            _context = context;
            _env = env;
         
        }

        public async Task<IActionResult> Index()
        {
            return _context.FileAssets != null ?
                        View(await _context.FileAssets.ToListAsync()) :
                        Problem("Entity set 'AppDbContext.FileAssets'  is null.");

        }

        public IActionResult downloadAll()
        {
            var ZipFile = $"docFile-{DateTime.Now.ToString("yyyy_MM-dd-HH_mm_ss")}.zip";

            using (var memorystream = new MemoryStream())
            {
                using(var archieve = new ZipArchive(memorystream,ZipArchiveMode.Create,true))
                {
                    _context.FileAssets.ToList().ForEach(files=>
                    {
                        var zipentry = archieve.CreateEntry(files.Filename);
                        var stringpath = Path.Combine(this._env.WebRootPath +  files.FileUrls);
                        byte[] bytes = System.IO.File.ReadAllBytes(stringpath);
                        using (var filems = new MemoryStream(bytes))
                            using(var openstream = zipentry.Open())
                        {
                            filems.CopyTo(openstream);
                        }

                    });
                }
                return File(memorystream.ToArray(), "application/zip", ZipFile);
            }
        }
    }
}

Create View

Open the Index.cshtml file and update the following code:

@model IEnumerable<WebApplication_Download_Files.Models.FileAssets>
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">File List to Download</h1>


    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Filename)
                </th>
                <th>
                    Action
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Filename)
                    </td>
                    
                    <td>
                        @Html.ActionLink("Download File","download",new{Filename = item.FileUrls  } )                        
                    </td>

                </tr>
            }
        </tbody>
    </table>
    <a asp-controller="Home" asp-action="downloadAll">Download All</a> 

</div>

output:

How to download multiple files in ASP.NET Core MVC

See Also:

Dynamic Middleware | Conditionally add middleware in ASP.NET Core

The post How to download multiple files in ASP.NET Core MVC appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-download-multiple-files-in-asp-net-core-mvc/feed/ 0 2121
How to download files using ASP.NET Core MVC https://reactconf.org/how-to-download-files-using-asp-net-core-mvc/ https://reactconf.org/how-to-download-files-using-asp-net-core-mvc/#respond Thu, 09 Nov 2023 11:53:29 +0000 https://labpys.com/?p=2103 This article explores how to download files using ASP.NET Core MVC. To begin, we have to create a table for storing file information, such as file names, and a source …

The post How to download files using ASP.NET Core MVC appeared first on Tech Insights.

]]>
This article explores how to download files using ASP.NET Core MVC. To begin, we have to create a table for storing file information, such as file names, and a source path. Here’s a step-by-step guide on How to download files in ASP.NET Core MVC.

Create an Asp.NET Core MVC Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web Application” from the list of available templates.
  • Click the Next button.
  • Then configure a new project, and specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Open the HomeController.cs file. Create a new method named download:

        public IActionResult download(string Filename)
        {
            var stringpath = Path.Combine(this._env.WebRootPath + Filename);
            byte[] bytes = System.IO.File.ReadAllBytes(stringpath);
             
            return File(bytes, "application/octet-stream", Filename);
        }

ASP.NET Core provides four file-related response classes that implement the ActionResult interface.

  • FileContentResult:
  • FileStreamResult:
  • VirtualFileResult:
  • PhysicalFileResult

The FileResult class is an abstract base class for all file-related response classes in ASP.NET Core. The specific class you use to return a file to the browser depends on how to provide the file content and from where.

  • FileContentResult and  FileStreamResult can be used to return files from virtual paths within your web application.
  • PhysicalFileResult can be used to return a file from the absolute file path.

Open the View Index.cshtml file and add the following code.

@model IEnumerable<WebApplication_Download_Files.Models.FileAssets>
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">File List to Download</h1>


    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Filename)
                </th>
                <th>
                    Action
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Filename)
                    </td>
                    
                    <td>
                        @Html.ActionLink("Download File","download",new{Filename = item.FileUrls  } )                        
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>

Output

How to download files using ASP.NET Core MVC

See Also:

Conditionally add middleware in ASP.NET Core

The post How to download files using ASP.NET Core MVC appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-download-files-using-asp-net-core-mvc/feed/ 0 2103
ASP.NET Core MVC | Populate DropdownList with Month Names Using LINQ https://reactconf.org/asp-net-core-mvc-populate-dropdownlist-with-month-names-using-linq/ https://reactconf.org/asp-net-core-mvc-populate-dropdownlist-with-month-names-using-linq/#respond Sun, 23 Apr 2023 00:35:00 +0000 https://labpys.com/?p=1154 A dropdown list is a commonly used control in ASP.NET Core MVC for allowing users to select an option from a list of things. Frequently, the dropdown list control’s list …

The post ASP.NET Core MVC | Populate DropdownList with Month Names Using LINQ appeared first on Tech Insights.

]]>
A dropdown list is a commonly used control in ASP.NET Core MVC for allowing users to select an option from a list of things. Frequently, the dropdown list control’s list of items includes a list of months from which the user can choose. Manually populating a dropdown list control with month names, on the other hand, might be time-consuming and inconvenient. In this post, we’ll look at how to use ASP.NET Core MVC | Populate DropdownList with Month Names Using LINQ.

Prerequisites

You will need the following to follow along with this tutorial:

  • NET Core SDK from here
  • Visual Studio or Visual Studio Code from here

Steps for ASP.NET Core MVC | Populate DropdownList with Month Names Using LINQ

Create a Dropdownlist control.

First, in our Razor view, we need to add a Dropdownlist control.

@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "Home Page";
}

<div class="row">
    <div class="col-md-4">
        <div class="form-group">
            <label class="control-label">Select Month</label>
            <select nme="getMonth" class="form-control" asp-items="@ViewBag.Month"></select>

        </div>
    </div>
</div>
ASP.NET Core MVC | Populate DropdownList with Month Names Using LINQ

Create a List of Month Names

The next step is to make a list of month names. We’ll use LINQ to generate a list of months, with the current month set as the default value.

 public IActionResult Index()
        {
          var GetMonth =  Enumerable.Range(1,12)
                .Select(m => new SelectListItem
                {
                    Text = new DateTimeFormatInfo().GetAbbreviatedMonthName(m),
                    Value = m.ToString()
                }).ToList();
                       
            ViewBag.Month = GetMonth; 
            return View();
        }
Document

Conclusion

Using LINQ to populate a Dropdownlist control with month names in ASP.NET Core is a simple process. You can rapidly construct a Dropdownlist control with a list of months for your users to select by following the methods explained in this article.

FAQs

  1. What exactly is LINQ?

LINQ is an acronym that stands for Language Integrated Query. It is a.NET language feature that allows developers to query several data sources using a uniform syntax.

2. Is it possible to associate the Dropdownlist control with a list of objects?

Yes, you may associate the Dropdownlist control with a collection of objects. Simply build a list of SelectListItem objects, where the Value property is the object’s ID and the Text property is the object’s name.

The post ASP.NET Core MVC | Populate DropdownList with Month Names Using LINQ appeared first on Tech Insights.

]]>
https://reactconf.org/asp-net-core-mvc-populate-dropdownlist-with-month-names-using-linq/feed/ 0 1154
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