Follow us

Header Ads

UploadViewImage In Asp.Net Core

UploadViewImage In Asp.Net Core

Packages

  • "Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.0" 
  • "Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0" 
  • "Microsoft.EntityFrameworkCore.Tools" Version="5.0.0"
  • "Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" 

Create  Images Folder in wwwroot Folder

Controllers[Folder]

HomeController.cs

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UploadViewImage.Data;
using UploadViewImage.Models;
using UploadViewImage.ViewModel;

namespace UploadViewImage.Controllers
{
    public class HomeController : Controller
    {
        private readonly ApplicationDbContext Context;
        private readonly IWebHostEnvironment WebHostEnvironment;
        
        public HomeController(ApplicationDbContext context,
            IWebHostEnvironment webHostEnvironment)
        {
            Context = context;
            WebHostEnvironment = webHostEnvironment;
        }
        public IActionResult Index()
        {
            var items = Context.Students.ToList();
            return View(items);
        }
        public IActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Create(StudentViewModel vm)
        {
            string stringFileName = UploadFile(vm);
               var Student = new Student
                {
                    Name = vm.Name,
                    ProfileImage = stringFileName
                };
            Context.Students.Add(Student);
            Context.SaveChanges();
            return RedirectToAction("Index");
                
        }

        private string UploadFile(StudentViewModel vm)
        {
            string fileName = null;
            if(vm.ProfileImage!=null)
            {
                string uploadDir = Path.Combine(WebHostEnvironment.WebRootPath, "Images");
                fileName = Guid.NewGuid().ToString() + "_" + vm.ProfileImage.FileName;
                string filePath = Path.Combine(uploadDir, fileName);
                using(var fileStream = new FileStream(filePath,FileMode.Create))
                {
                    vm.ProfileImage.CopyTo(fileStream);
                }
            }
            return fileName;
        }
    }
}

Data[Folder]

ApplicationDbContext.cs

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UploadViewImage.Models;

namespace UploadViewImage.Data
{//Application DbContext is inherited with DbContextClass
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {

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

Models[Fodler]

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

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

ViewModel[Folder]

StudentViewModel.cs

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace UploadViewImage.ViewModel
{
    public class StudentViewModel
    {
        public string Name { get; set; }
        //IFormFile can automatically create chose image option
        public IFormFile ProfileImage { get; set; }
    }
}


Views[Folder]

Home

Create.cshtml

@model UploadViewImage.ViewModel.StudentViewModel

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

<h1>Create</h1>

<h4>StudentViewModel</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ProfileImage" class="control-label"></label>
                <input asp-for="ProfileImage" class="form-control" />
                <span asp-validation-for="ProfileImage" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Index.cshtml

@model IEnumerable<UploadViewImage.Models.Student>

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

<h1>Index</h1>

<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.ProfileImage)
            </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>
              <img src="~/Images/@item.ProfileImage" class="rounded-circle" width="40" height="40" asp-append-version="true" />
            </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>

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=CHETUIWK0541\\SQL2019NEW;Database=DisplayImage;Trusted_Connection=True;MultipleActiveResultSets=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UploadViewImage.Data;

namespace UploadViewImage
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

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

Post a Comment

0 Comments