Apr 16, 2018

Image Gallery - Image Add/Delete/Preview - Single Page App -


https://github.com/TheKalin/jQuery-File-Upload.MVC5

Helper Class / Models

 public class FilesHelperDB

    {
        dbImageGalleryEntities1 _dbContext = new dbImageGalleryEntities1();


        String DeleteURL = null;
        String DeleteType = null;
        String StorageRoot = null;
        String UrlBase = null;
        String tempPath = null;
        //ex:"~/Files/something/";
        String serverMapPath = null;
        public FilesHelperDB(String DeleteURL, String DeleteType, String StorageRoot, String UrlBase, String tempPath, String serverMapPath)
        {
            this.DeleteURL = DeleteURL;
            this.DeleteType = DeleteType;
            this.StorageRoot = StorageRoot;
            this.UrlBase = UrlBase;
            this.tempPath = tempPath;
            this.serverMapPath = serverMapPath;
        }

        public void DeleteFiles(String pathToDelete)
        {

            string path = HostingEnvironment.MapPath(pathToDelete);

            System.Diagnostics.Debug.WriteLine(path);
            if (Directory.Exists(path))
            {
                DirectoryInfo di = new DirectoryInfo(path);
                foreach (FileInfo fi in di.GetFiles())
                {
                    System.IO.File.Delete(fi.FullName);
                    System.Diagnostics.Debug.WriteLine(fi.Name);
                }

                di.Delete(true);
            }
        }
        public String DeleteFile(String file)
        {
            System.Diagnostics.Debug.WriteLine("DeleteFile");
            //    var req = HttpContext.Current;
            System.Diagnostics.Debug.WriteLine(file);

            String fullPath = Path.Combine(StorageRoot, file);
            System.Diagnostics.Debug.WriteLine(fullPath);
            System.Diagnostics.Debug.WriteLine(System.IO.File.Exists(fullPath));
            String thumbPath = "/" + file + "80x80.jpg";
            String partThumb1 = Path.Combine(StorageRoot, "thumbs");
            String partThumb2 = Path.Combine(partThumb1, file + "80x80.jpg");

            System.Diagnostics.Debug.WriteLine(partThumb2);
            System.Diagnostics.Debug.WriteLine(System.IO.File.Exists(partThumb2));
            if (System.IO.File.Exists(fullPath))
            {
                //delete thumb
                if (System.IO.File.Exists(partThumb2))
                {
                    System.IO.File.Delete(partThumb2);
                }
                System.IO.File.Delete(fullPath);
                String succesMessage = "Ok";
                return succesMessage;
            }
            String failMessage = "Error Delete";
            return failMessage;
        }
        public JsonFiles GetFileList()
        {
            var r = new List<ViewDataUploadFilesResult>();
            String fullPath = Path.Combine(StorageRoot);

            List<string> imgNameDB =(from a in  _dbContext.tblImages where (a.isDelete == 1)  select a.ImageName).ToList();

            if (Directory.Exists(fullPath))
            {
                DirectoryInfo dir = new DirectoryInfo(fullPath);
                foreach (FileInfo file in dir.GetFiles())
                {
                    if(imgNameDB.Contains(file.Name))
                    {
                        string imgId = file.Name.Substring(3);
                        int indexOfDot = imgId.LastIndexOf('.');
                        imgId = imgId.Substring(0, indexOfDot);


                        int SizeInt = unchecked((int)file.Length);
                        r.Add(UploadResult(imgId,file.Name, SizeInt, file.FullName));
                    }               
                }
            }
            JsonFiles files = new JsonFiles(r);

            return files;
        }

        public void UploadAndShowResults(HttpContextBase ContentBase, List<ViewDataUploadFilesResult> resultList)
        {
            var httpRequest = ContentBase.Request;
            System.Diagnostics.Debug.WriteLine(Directory.Exists(tempPath));

            String fullPath = Path.Combine(StorageRoot);
            Directory.CreateDirectory(fullPath);
            // Create new folder for thumbs
            Directory.CreateDirectory(fullPath + "/thumbs/");

            foreach (String inputTagName in httpRequest.Files)
            {

                var headers = httpRequest.Headers;

                var file = httpRequest.Files[inputTagName];
                System.Diagnostics.Debug.WriteLine(file.FileName);

                if (string.IsNullOrEmpty(headers["X-File-Name"]))
                {

                    UploadWholeFile(ContentBase, resultList);
                }
                else
                {

                    UploadPartialFile(headers["X-File-Name"], ContentBase, resultList);
                }
            }
        }

        public int fetchID()
        {
            int n=0;
            try
            {         
                n = _dbContext.tblImages.Max(p => p.ImageId);
            }
            catch(Exception ex) { }
            return n;
        }
        private void UploadWholeFile(HttpContextBase requestContext, List<ViewDataUploadFilesResult> statuses)
        {
            int n = fetchID() + 1;

            var request = requestContext.Request;
            for (int i = 0; i < request.Files.Count; i++)
            {
                var file = request.Files[i];

                //Change filename as per sequence
                string extension1 = Path.GetExtension(file.FileName);
                var filename1 = "img"+ n.ToString() + extension1;

                //Save image to DB
                tblImage img1 = new tblImage()
                {
                    ImageName = filename1,
                    isDelete = 1,
                    AdddDate = DateTime.UtcNow                 
                };
                _dbContext.tblImages.Add(img1);
                int imgID = _dbContext.SaveChanges();

                String pathOnServer = Path.Combine(StorageRoot);
                var fullPath = Path.Combine(pathOnServer, filename1);
                file.SaveAs(fullPath);

                //Create thumb
                string[] imageArray = file.FileName.Split('.');
                if (imageArray.Length != 0)
                {
                    String extansion = imageArray[imageArray.Length - 1].ToLower();
                    if (extansion != "jpg" && extansion != "png" && extansion != "jpeg") //Do not create thumb if file is not an image
                    {

                    }
                    else
                    {
                        var ThumbfullPath = Path.Combine(pathOnServer, "thumbs");
                        //String fileThumb = file.FileName + ".80x80.jpg";
                        String fileThumb = "img" + n.ToString() + "80x80.jpg";
                        var ThumbfullPath2 = Path.Combine(ThumbfullPath, fileThumb);
                        using (MemoryStream stream = new MemoryStream(System.IO.File.ReadAllBytes(fullPath)))
                        {
                            var thumbnail = new WebImage(stream).Resize(80, 80);
                            thumbnail.Save(ThumbfullPath2, "jpg");
                        }
                    }
                }
                statuses.Add(UploadResult(img1.ImageId.ToString(),filename1, file.ContentLength, filename1));
            }
        }

        private void UploadPartialFile(string fileName, HttpContextBase requestContext, List<ViewDataUploadFilesResult> statuses)
        {
            var request = requestContext.Request;
            if (request.Files.Count != 1) throw new HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request");
            var file = request.Files[0];
            var inputStream = file.InputStream;
            String patchOnServer = Path.Combine(StorageRoot);
            var fullName = Path.Combine(patchOnServer, Path.GetFileName(file.FileName));
            var ThumbfullPath = Path.Combine(fullName, Path.GetFileName(file.FileName + "80x80.jpg"));
            ImageHandler handler = new ImageHandler();

            var ImageBit = ImageHandler.LoadImage(fullName);
            handler.Save(ImageBit, 80, 80, 10, ThumbfullPath);
            using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write))
            {
                var buffer = new byte[1024];

                var l = inputStream.Read(buffer, 0, 1024);
                while (l > 0)
                {
                    fs.Write(buffer, 0, l);
                    l = inputStream.Read(buffer, 0, 1024);
                }
                fs.Flush();
                fs.Close();
            }
            statuses.Add(UploadResult("",file.FileName, file.ContentLength, file.FileName));
        }
        public ViewDataUploadFilesResult UploadResult(string imgId1,String FileName, int fileSize, String FileFullPath)
        {
            String getType = System.Web.MimeMapping.GetMimeMapping(FileFullPath);
            var result = new ViewDataUploadFilesResult()
            {
                imgId = imgId1,
                name = FileName,
                size = fileSize,
                type = getType,
                url = UrlBase + FileName,
                deleteUrl = DeleteURL + imgId1,
                thumbnailUrl = CheckThumb(getType, FileName),
                deleteType = DeleteType,
            };
            return result;
        }

        public String CheckThumb(String type, String FileName)
        {
            var splited = type.Split('/');
            if (splited.Length == 2)
            {
                string extansion = splited[1].ToLower();
                if (extansion.Equals("jpeg") || extansion.Equals("jpg") || extansion.Equals("png") || extansion.Equals("gif"))
                {
                    String thumbnailUrl = UrlBase + "thumbs/" + Path.GetFileNameWithoutExtension(FileName) + "80x80.jpg";
                    return thumbnailUrl;
                }
                else
                {
                    if (extansion.Equals("octet-stream")) //Fix for exe files
                    {
                        return "/Content/Free-file-icons/48px/exe.png";

                    }
                    if (extansion.Contains("zip")) //Fix for exe files
                    {
                        return "/Content/Free-file-icons/48px/zip.png";
                    }
                    String thumbnailUrl = "/Content/Free-file-icons/48px/" + extansion + ".png";
                    return thumbnailUrl;
                }
            }
            else
            {
                return UrlBase + "/thumbs/" + Path.GetFileNameWithoutExtension(FileName) + "80x80.jpg";
            }

        }
        public List<String> FilesList()
        {
            List<String> Filess = new List<String>();
            string path = HostingEnvironment.MapPath(serverMapPath);
            System.Diagnostics.Debug.WriteLine(path);
            if (Directory.Exists(path))
            {
                DirectoryInfo di = new DirectoryInfo(path);
                foreach (FileInfo fi in di.GetFiles())
                {
                    Filess.Add(fi.Name);
                    System.Diagnostics.Debug.WriteLine(fi.Name);
                }

            }
            return Filess;
        }
    }


   public class ImageHandler

    {
            /// <summary>
            /// Method to resize, convert and save the image.
            /// </summary>
            /// <param name="image">Bitmap image.</param>
            /// <param name="maxWidth">resize width.</param>
            /// <param name="maxHeight">resize height.</param>
            /// <param name="quality">quality setting value.</param>
            /// <param name="filePath">file path.</param>   
            public void Save(Bitmap image, int maxWidth, int maxHeight, int quality, string filePath)
            {
                // Get the image's original width and height
                int originalWidth = image.Width;
                int originalHeight = image.Height;

                // To preserve the aspect ratio
                float ratioX = (float)maxWidth / (float)originalWidth;
                float ratioY = (float)maxHeight / (float)originalHeight;
                float ratio = Math.Min(ratioX, ratioY);

                // New width and height based on aspect ratio
                int newWidth = (int)(originalWidth * ratio);
                int newHeight = (int)(originalHeight * ratio);

                // Convert other formats (including CMYK) to RGB.
                Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);

                // Draws the image in the specified size with quality mode set to HighQuality
                using (Graphics graphics = Graphics.FromImage(newImage))
                {
                    graphics.CompositingQuality = CompositingQuality.HighQuality;
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.SmoothingMode = SmoothingMode.HighQuality;
                    graphics.DrawImage(image, 0, 0, newWidth, newHeight);
                }

                // Get an ImageCodecInfo object that represents the JPEG codec.
                ImageCodecInfo imageCodecInfo = this.GetEncoderInfo(ImageFormat.Jpeg);

                // Create an Encoder object for the Quality parameter.
                System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;

                // Create an EncoderParameters object.
                EncoderParameters encoderParameters = new EncoderParameters(1);

                // Save the image as a JPEG file with quality level.
                EncoderParameter encoderParameter = new EncoderParameter(encoder, quality);
                encoderParameters.Param[0] = encoderParameter;
                newImage.Save(filePath, imageCodecInfo, encoderParameters);
            }

            /// <summary>
            /// Method to get encoder infor for given image format.
            /// </summary>
            /// <param name="format">Image format</param>
            /// <returns>image codec info.</returns>
            private ImageCodecInfo GetEncoderInfo(ImageFormat format)
            {
                return ImageCodecInfo.GetImageDecoders().SingleOrDefault(c => c.FormatID == format.Guid);
            }
            public static Bitmap LoadImage(string path)
            {
                var ms = new MemoryStream(File.ReadAllBytes(path));
                GC.KeepAlive(ms);
                return (Bitmap)Image.FromStream(ms);
            }
            public static Size GetThumbnailSize(Image original)
            {
                // Maximum size of any dimension.
                const int maxPixels = 40;

                // Width and height.
                int originalWidth = original.Width;
                int originalHeight = original.Height;

                // Compute best factor to scale entire image based on larger dimension.
                double factor;
                if (originalWidth > originalHeight)
                {
                    factor = (double)maxPixels / originalWidth;
                }
                else
                {
                    factor = (double)maxPixels / originalHeight;
                }

                // Return thumbnail size.
                return new Size((int)(originalWidth * factor), (int)(originalHeight * factor));
            }
        }

 public class FilesViewModel    {

        public ViewDataUploadFilesResult[] Files { get; set; }
    }


Controller

   public class HomeController : Controller    {


        dbImageGalleryEntities1 _dbContext = new dbImageGalleryEntities1();
        FilesHelper filesHelper;
        FilesHelperDB filesHelperDB;
        String tempPath = "~/somefiles/";
        String serverMapPath = "~/Files/somefiles/";
        private string StorageRoot
        {
            get { return Path.Combine(HostingEnvironment.MapPath(serverMapPath)); }
        }
        private string UrlBase = "/Files/somefiles/";
        String DeleteURL = "/Home/deleteImageDB/?Id=";
        String DeleteType = "GET";

        public HomeController()
        {
            filesHelper = new FilesHelper(DeleteURL, DeleteType, StorageRoot, UrlBase, tempPath, serverMapPath);
            filesHelperDB = new FilesHelperDB(DeleteURL, DeleteType, StorageRoot, UrlBase, tempPath, serverMapPath);
        }
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult addImagesToFile(string viewName)
        {
            JsonFiles ListOfFiles = filesHelper.GetFileList();
            var model = new FilesViewModel()
            {
                Files = ListOfFiles.files
            };
            return PartialView(viewName);
        }     
        [HttpPost]
        public JsonResult UploadToFile()
        {
            var resultList = new List<ViewDataUploadFilesResult>();

            var CurrentContext = HttpContext;

            filesHelper.UploadAndShowResults(CurrentContext, resultList);
            JsonFiles files = new JsonFiles(resultList);

            bool isEmpty = !resultList.Any();
            if (isEmpty)
            {
                return Json("Error ");
            }
            else
            {
                return Json(files);
            }
        }
        public ActionResult ShowFromFile()
        {
            JsonFiles ListOfFiles = filesHelper.GetFileList();
            var model = new FilesViewModel()
            {
                Files = ListOfFiles.files
            };         
            return PartialView("_partialImageToFileGrid", model);
        }


        public ActionResult imageToDB(string viewName)
        {
            return View(viewName);
        }
        //public ActionResult addImagesToDB(string viewName)
        //{       
        //    return PartialView(viewName);
        //}

        [HttpPost]
        public JsonResult UploadToDB()
        {
            var resultList = new List<ViewDataUploadFilesResult>();

            var CurrentContext = HttpContext;

            filesHelperDB.UploadAndShowResults(CurrentContext, resultList);
            JsonFiles files = new JsonFiles(resultList);

            //bool isEmpty = !resultList.Any();
            //if (isEmpty)
            //{
            //    return Json("Error ");
            //}
            //else
            //{
            //    return Json(files);
            //}
            return Json("OK", JsonRequestBehavior.AllowGet);
        }
        public ActionResult ShowFromDB()
        {
            JsonFiles ListOfFiles = filesHelperDB.GetFileList();
            var model = new FilesViewModel()
            {
                Files = ListOfFiles.files
            };
            return PartialView("_partialImageToDBGrid", model);
        }

        [HttpGet]
        public ActionResult deleteImageDB(string Id)
        {
            try
            {
                int Id1 = int.Parse(Id);
                var img1 = _dbContext.tblImages.FirstOrDefault(x => x.ImageId == Id1);
                img1.isDelete = 0;             
                _dbContext.SaveChanges();
            }
            catch (Exception ex) { }
            return Json("OK", JsonRequestBehavior.AllowGet);
        }

        public ActionResult createAlbum(string viewName)
        {
            return PartialView(viewName);
        }
    }


Views 

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/jQuery-File-Upload")
    @Styles.Render("~/Content/jQuery-File-Upload")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/jQuery-File-Upload")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
     
    @RenderSection("scripts", required: false)
</body>
</html>

_partialImageToDB.cshtml

@model ImageGallery.Models.FilesViewModel
<div class="container">
    <div id="addImagesDB">
        @Html.Partial("_partialImageToDBAdd")
    </div>
</div>
<hr />
<div id="displayImagesDB">
    @if (Model == null)
    {
        Html.RenderPartial("_partialImageToDBGrid", new ImageGallery.Models.FilesViewModel());
    }
    else
    {
        Html.RenderPartial("_partialImageToDBGrid", Model);
    }
</div>
<script>
    $(document).ready(function () {
        $.ajax({
            url: '@Url.Action("ShowFromDB", "Home")',
            type: "GET",
            success: function (data) {
                $('#displayImagesDB').html(data);
            },
            error: function (e) {              
            }
        });
    });
</script>

_partialImageToDBAdd.cshtml

@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>

<script>
    var $form = null;
    $(function () {
        $form = $('#fileupload1').fileupload({
            dataType: 'json'
        });
    });
  //  $('#fileupload1').addClass('fileupload-processing');
</script>
@Html.Partial("_FilesFromDB")

_partialImageToDBGrid.cshtml

@model ImageGallery.Models.FilesViewModel
@using ImageGallery.Helpers
<link href="~/Content/sweetalert.css" rel="stylesheet" />
<script src="~/Content/sweetalert.js"></script>
<style>
    .abcd {
        text-align: center;
        float: left;
        position: relative;
    }

        .abcd img {
            border-radius: 25px;
            background: #ffffff;
            margin-left: 10px;
            margin-top: 10px;
            height: 100px;
            width: 100px;
            padding: 5px;
            border: 1px solid rgb(232, 222, 189);
        }

    .abcd1 img {
        border-radius: 25px;
        background: #ffffff;
        margin-left: 10px;
        margin-top: 5px;
        padding: 5px;
        border: 1px solid rgb(232, 222, 189);
    }

    .closeIcon {
        position: absolute;
        cursor: pointer;
        float: right;
        right: -3px;
        top: 3px;
        background: rgba(0,0,0,0.5);
        display: block;
        height: 20px;
        width: 20px;
        z-index: 222;
        color: white;
        text-align: center;
        line-height: 20px;
        border-radius: 25px;
    }

    .image_gallery {
        display: inline-block;
        width: 154px;
    }
</style>
<h2>Show</h2>

<div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls" data-filter=":even">
    <div class="slides"></div>
    <h3 class="title"></h3>
    <a class="prev">‹</a>
    <a class="next">›</a>
    <a class="close">×</a>
    <a class="play-pause"></a>
    <ol class="indicator"></ol>
</div>

<div id="links">
    @if (@Model.Files != null && @Model.Files.Length != 0)
    {
        foreach (ViewDataUploadFilesResult file in @Model.Files)
        {
            if (file.type.Equals("video/mp4"))
            {
                <div id="abcd" class='abcd'>
                    <a href="@file.url" title="@file.name" type="video/mp4" data-description="This is a movie."><img src="@file.thumbnailUrl" alt="@file.name"><i id="@file.imgId" class="glyphicon glyphicon-remove closeIcon"></i></a>
                </div>
            }
            else
            {
                <div id="abcd" class='abcd'>
                    <a href="@file.url" title="@file.name" data-description="This is a image."><img src="@file.thumbnailUrl" alt="@file.name"><i id="@file.imgId" class="glyphicon glyphicon-remove closeIcon"></i></a>
                </div>
            }
        }
    }
    else
    {
        <p>No files</p>
    }

</div>

<script>
    $("i").click(function () {
        alert(this.id);
        var obj = this;
        var imgId = this.id;
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this Image!",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes, delete it!",
            cancelButtonText: "No, cancel plx!",
            closeOnConfirm: true,
            closeOnCancel: false
        },
               function (isConfirm) {
                   if (isConfirm) {
                       $.get('@Url.Action("deleteImageDB", "Home")', { Id: imgId }, function (data) { });                     
                       $(obj).parent().parent().remove();
                   } else {
                       swal("Cancelled", "Your Record is safe :)", "error");
                   }
               });


        return false;
    });

    document.getElementById('links').onclick = function (event) {
        event = event || window.event;
        var target = event.target || event.srcElement,
            link = target.src ? target.parentNode : target,
            options = { index: link, event: event },
            links = this.getElementsByTagName('a');
        blueimp.Gallery(links, options);
    };
</script>

_FilesFromDB.cshtml


<h2>jQuery File Upload</h2>
<form id="fileupload1" method="POST" enctype="multipart/form-data" data-url="@Url.Action("UploadToDB","Home")">
    <div class="row fileupload-buttonbar">
        <div class="col-lg-7">
            <!-- The fileinput-button span is used to style the file input field as button -->
            <span class="btn btn-success fileinput-button">
                <i class="glyphicon glyphicon-plus"></i>
                <span>Add files...</span>
                <input type="file" name="files[]" multiple>
            </span>
            <button type="submit" class="btn btn-primary start">
                <i class="glyphicon glyphicon-upload"></i>
                <span>Start upload</span>
            </button>
            <button type="reset" class="btn btn-warning cancel">
                <i class="glyphicon glyphicon-ban-circle"></i>
                <span>Cancel upload</span>
            </button>
            <button type="button" class="btn btn-danger delete">
                <i class="glyphicon glyphicon-trash"></i>
                <span>Delete</span>
            </button>
            <input type="checkbox" class="toggle">
            <!-- The global file processing state -->
            <span class="fileupload-process"></span>
        </div>
        <!-- The global progress state -->
        <div class="col-lg-5 fileupload-progress fade">
            <!-- The global progress bar -->
            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                <div class="progress-bar progress-bar-success" style="width:0%;"></div>
            </div>
            <!-- The extended global progress state -->
            <div class="progress-extended">&nbsp;</div>
        </div>
    </div>
    <!-- The global progress state -->
    <div class="col-lg-5 fileupload-progress fade">
        <!-- The global progress bar -->
        <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
            <div class="progress-bar progress-bar-success" style="width:0%;"></div>
        </div>
        <!-- The extended global progress state -->
        <div class="progress-extended">&nbsp;</div>
    </div>

    <!-- The table listing the files available for upload/download -->
    <table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
</form>
<br>
<!-- The blueimp Gallery widget -->
<div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls" data-filter=":even">
    <div class="slides"></div>
    <h3 class="title"></h3>
    <a class="prev">‹</a>
    <a class="next">›</a>
    <a class="close">×</a>
    <a class="play-pause"></a>
    <ol class="indicator"></ol>
</div>
<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
    {% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-upload fade">
        <td>
            <span class="preview"></span>
        </td>
        <td>
            <p class="name">{%=file.name%}</p>
            <strong class="error text-danger"></strong>
        </td>
        <td>
            <p class="size">Processing...</p>
            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
        </td>
        <td>
            {% if (!i && !o.options.autoUpload) { %}
            <button class="btn btn-primary start" disabled>
                <i class="glyphicon glyphicon-upload"></i>
                <span>Start</span>
            </button>
            {% } %}
            {% if (!i) { %}
            <button class="btn btn-warning cancel">
                <i class="glyphicon glyphicon-ban-circle"></i>
                <span>Cancel</span>
            </button>
            {% } %}
        </td>
    </tr>
    {% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
    @*{% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-download fade">
        <td>
            <span class="preview">
                {% if (file.thumbnailUrl) { %}
                <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>
                {% } %}
            </span>
        </td>
        <td>
            <p class="name">
                {% if (file.url) { %}
                <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
                {% } else { %}
                <span>{%=file.name%}</span>
                {% } %}
            </p>
            {% if (file.error) { %}
            <div><span class="label label-danger">Error</span> {%=file.error%}</div>
            {% } %}
        </td>
        <td>
            <span class="size">{%=o.formatFileSize(file.size)%}</span>
        </td>
        <td>
            {% if (file.deleteUrl) { %}
            <button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}" {% if (file.deletewithcredentials) { %} data-xhr-fields='{"withCredentials":true}' {% } %}>
                <i class="glyphicon glyphicon-trash"></i>
                <span>Delete</span>
            </button>
            <input type="checkbox" name="delete" value="1" class="toggle">
            {% } else { %}
            <button class="btn btn-warning cancel">
                <i class="glyphicon glyphicon-ban-circle"></i>
                <span>Cancel</span>
            </button>
            {% } %}
        </td>
    </tr>
    {% } %}*@
</script>





Apr 12, 2018

MVC - Strongly Typed - Drop Down - Checkbox - Partial View - image - Approve - Multiselect - Remote Validation - Unobtrusive Validation

Models

    public class User1
    {
        public int User_ID { get; set; }

        [Required(ErrorMessage = "Required..")]
        public string FName { get; set; }

        [Required(ErrorMessage = "Required..")]
        public string LName { get; set; }

        [Required(ErrorMessage = "Required..")]
        public string Mobile { get; set; }

        [RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "E-mail is not valid")]
        [Remote("IsUserExists", "Home", HttpMethod = "POST", ErrorMessage = "User name Already taken...")]
        public string Email { get; set; }

        public string Gender { get; set; }

        public string ImageUrl { get; set; }

        public string isApproved { get; set; }

        public List<GameType1> GameTypeList { get; set; }
        public int GameTypeId { get; set; }

        public List<SelectListItem> GameList1 { get; set; }
        public IList<int> GameSelected { get; set; }

        public List<GameList1> GameList2 { get; set; }
        public string GameList { get; set; }
    }

    public class GameType1
    {
        public bool Selected { get; set; }
        public int GameType_Id { get; set; }
        public string GameType { get; set; }
    }

    public class GameList1
    {
        public int Game_Id { get; set; }
        public string GameName { get; set; }
        public bool IsTrue { get; set; }
    }

Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Reg_Img_Approve.Models;
using System.IO;

namespace Reg_Img_Approve.Controllers
{
    public class HomeController : Controller
    {
        Reg_MultiSelectEntities _dbContext = new Reg_MultiSelectEntities();
        public ActionResult Index()
        {
            User1 user1 = new User1();
            List<GameType1> info1 = (from a in _dbContext.tblGameTypes
                                     select new GameType1
                                     {
                                         GameType_Id = a.GameType_ID,
                                         GameType = a.GameType
                                     }).ToList();
            user1.User_ID = 0;
            user1.GameTypeList = info1;
            user1.GameTypeId = 1;
            user1.GameList1 = new List<SelectListItem>();
            return View(user1);
        }

        [HttpPost]
        public ActionResult addEditUserDetail(User1 model, HttpPostedFileBase files)
        {
            string path1 = "";
            if (model.User_ID == 0)
            {
                var image = files;
                if (image != null)
                {
                    //string extension1 = Path.GetExtension(image.FileName);
                    //var filename1 = n.ToString() + extension1;
                    path1 = Path.Combine(Server.MapPath("~/Upload/"), image.FileName);
                    model.ImageUrl = "Upload/" + image.FileName; ;
                }
                var user1 = new tblUser()
                {
                    FName = model.FName,
                    LName = model.LName,
                    Email = model.Email,
                    Mobile = model.Mobile,
                    Gender = model.Gender,
                    isApproved = 2,
                    ImageUrl = model.ImageUrl
                };
                _dbContext.tblUsers.Add(user1);
                foreach (var item in model.GameSelected)
                {
                    var data1 = new tblUserGame()
                    {
                        User_ID = user1.User_ID,
                        Game_ID = item
                    };
                    _dbContext.tblUserGames.Add(data1);
                }


                image.SaveAs(path1);
                _dbContext.SaveChanges();

            }
            else
            {
                try
                {
                    var user1 = _dbContext.tblUsers.FirstOrDefault(x => x.User_ID == model.User_ID);
                    var image = files;
                    if (image != null)
                    {
                        path1 = Path.Combine(Server.MapPath("~/Upload/"), image.FileName);
                        model.ImageUrl = "Upload/" + image.FileName;
                    }
                    var user2 = new tblUser()
                    {
                        User_ID = model.User_ID,
                        FName = model.FName,
                        LName = model.LName,
                        Email = model.Email,
                        Mobile = model.Mobile,
                        Gender = model.Gender,
                        isApproved = int.Parse(model.isApproved),
                        ImageUrl = model.ImageUrl
                    };
                    _dbContext.Entry(user1).CurrentValues.SetValues(user2);
                    //_dbContext.SaveChanges();
                    List<int> GameSelected = _dbContext.tblUserGames.Where(p => p.User_ID == model.User_ID).Select(p => p.Game_ID).ToList(); ;


                    if (model.GameSelected != null)
                    {
                        foreach (var item in model.GameSelected)
                        {
                            if (!GameSelected.Contains(item))
                            {
                                var data2 = new tblUserGame()
                                {
                                    User_ID = user1.User_ID,
                                    Game_ID = item
                                };
                                _dbContext.tblUserGames.Add(data2);
                            }
                        }

                        foreach (var item in GameSelected)
                        {
                            if (!model.GameSelected.Contains(item))
                            {
                                var data3 = _dbContext.tblUserGames.FirstOrDefault(x => x.User_ID == model.User_ID && x.Game_ID == item);
                                _dbContext.tblUserGames.Remove(data3);
                            }
                        }
                    }
                    else
                    {
                        foreach (var item in GameSelected)
                        {
                            var data3 = _dbContext.tblUserGames.FirstOrDefault(x => x.User_ID == model.User_ID && x.Game_ID == item);
                            _dbContext.tblUserGames.Remove(data3);
                        }
                    }

                    if (path1 != "")
                        image.SaveAs(path1);
                    _dbContext.SaveChanges();
                }
                catch (Exception ex) { }
            }
            var result = new { Success = "False", Message = "Error Message" };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult getGameList(string gameTypeId, string userId)
        {
            List<SelectListItem> gameLists1 = new List<SelectListItem>();
            List<int> GameSelected = new List<int>();
            try
            {
                if (userId != null && userId != "")
                {
                    int userID = int.Parse(userId);
                    GameSelected = _dbContext.tblUserGames.Where(p => p.User_ID == userID).Select(p => p.Game_ID).ToList();
                }
                int n = int.Parse(gameTypeId);
                gameLists1 = (from a in _dbContext.tblGames.Where(x => x.GameType_ID == n)
                              select new SelectListItem
                              {
                                  Value = a.Game_ID.ToString(),
                                  Text = a.GameName,
                                  Selected = GameSelected.Contains(a.Game_ID)
                              }).ToList();
            }
            catch (Exception ex) { }
            return PartialView("~/Views/Home/_partialGameList.cshtml", gameLists1);
        }

        public ActionResult loadUserGrid()
        {
            List<tblUser> userData1 = new List<tblUser>();
            List<User1> userData2 = new List<User1>();
            try
            {
                userData1 = _dbContext.tblUsers.ToList();

                foreach (var item in userData1)
                {
                    List<int> GameSelected = _dbContext.tblUserGames.Where(p => p.User_ID == item.User_ID).Select(p => p.Game_ID).ToList();
                    List<tblGame> gameList = (_dbContext.tblGames.Where(x => GameSelected.Contains(x.Game_ID))).ToList();
                    var data = new User1
                    {
                        User_ID = item.User_ID,
                        FName = item.FName,
                        Email = item.Email,
                        Mobile = item.Mobile,
                        ImageUrl = item.ImageUrl,
                        isApproved = item.isApproved.Value.ToString(),
                        GameList = string.Join(" , ", gameList.Select(x => x.GameName))
                    };
                    userData2.Add(data);
                }
            }
            catch (Exception ex) { }
            return Json(new { data = userData2 }, JsonRequestBehavior.AllowGet);
        }

        public string RetrieveImage1(string id)
        {
            int ID = int.Parse(id);
            string imagePath = (from temp in _dbContext.tblUsers where temp.User_ID == ID select temp.ImageUrl).FirstOrDefault();
            if (imagePath != null)
            {
                return "~/Upload/" + imagePath;
            }
            else
            {
                return "~/Upload/default.png";
            }
        }

        public ActionResult getUserData(string id)
        {
            tblUser user = new tblUser();
            User1 user1 = new User1();

            int GameType_ID1 = 0;
            try
            {
                int n = int.Parse(id);
                user = _dbContext.tblUsers.FirstOrDefault(x => x.User_ID == n);

                List<GameType1> info1 = (from a in _dbContext.tblGameTypes
                                         select new GameType1
                                         {
                                             GameType_Id = a.GameType_ID,
                                             GameType = a.GameType
                                         }).ToList();

                List<int> gamesId = (from a in _dbContext.tblUserGames.Where(x => x.User_ID == n) select a.Game_ID).ToList();
                List<int> GameType_ID = (from a in _dbContext.tblGames.Where(x =>gamesId.Contains(x.Game_ID)) select a.GameType_ID.Value).ToList() ;
                
                GameType_ID1 = GameType_ID.Count != 0 ? GameType_ID[0] : 1;
                user1.User_ID = user.User_ID;
                user1.FName = user.FName;
                user1.LName = user.LName;
                user1.Mobile = user.Mobile;
                user1.Email = user.Email;
                user1.Gender = user.Gender;
                user1.GameTypeList = info1;
                user1.GameTypeId = GameType_ID1;
                user1.ImageUrl = user.ImageUrl;

                user1.GameSelected = _dbContext.tblUserGames.Where(p => p.User_ID == user.User_ID).Select(p => p.Game_ID).ToList();
                List<SelectListItem> gameLists1 = new List<SelectListItem>();
                gameLists1 = (from a in _dbContext.tblGames.Where(x => x.GameType_ID == GameType_ID1)
                              select new SelectListItem
                              {
                                  Value = a.Game_ID.ToString(),
                                  Text = a.GameName,
                                  Selected = user1.GameSelected.Contains(a.Game_ID)
                              }).ToList();

                user1.GameList1 = gameLists1;
            }
            catch (Exception ex) { }
            return PartialView("_partialUserAdd", user1);
        }

        [HttpPost]
        public ActionResult creatApproveMemberList(string[] memberIDs)
        {
            try
            {
                foreach (string id in memberIDs)
                {
                    string[] words = id.Split('_');

                    if (words[1] == "A")
                    {
                        int id1 = int.Parse(words[0]);
                        var user1 = _dbContext.tblUsers.FirstOrDefault(x => x.User_ID == id1);
                        user1.isApproved = 1;
                        _dbContext.SaveChanges();

                        //Guid memberId = Guid.Parse(words[0]);
                        //Gang_MemberDetails member1 = _dbContext.Gang_MemberDetails.FirstOrDefault(x => x.MemberId == memberId);
                        //member1.MemberStatus = 1;
                        //member1.ReviewbyAgentId = User.Identity.GetUserId();
                        //member1.ReviewDate = DateTime.Today;
                        //_dbContext.SaveChanges();
                    }
                    else
                    {
                        int id1 = int.Parse(words[0]);
                        var user1 = _dbContext.tblUsers.FirstOrDefault(x => x.User_ID == id1);
                        user1.isApproved = 0;
                        _dbContext.SaveChanges();
                    }
                }
            }
            catch (Exception ex) { }
            return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
        }


        [HttpPost]
        public JsonResult IsUserExists(string Email)
        {
            bool isValid = !_dbContext.tblUsers.Any(x => x.Email == Email);
            return Json(isValid, JsonRequestBehavior.AllowGet);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

Apr 11, 2018

MVC - Strongly Typed - Drop Down - Checkbox - Partial View - image - Approve - Multiselect


Models

 public class GameUser1
 {
        public int User_ID { get; set; }

        [Required(ErrorMessage = "Required..")]
        public string FName { get; set; }

        [Required(ErrorMessage = "Required..")]
        public string Mobile { get; set; }

        [Required(ErrorMessage = "Required..")]
        public string Email { get; set; }

        public List GameTypeList { get; set; }
        public int GameTypeId { get; set; }

        public List GameList1 { get; set; }
        public IList GameSelected { get; set; }

        public List GameList2 { get; set; }
        public string GameList { get; set; }
 }

  public class GameList1
  {
        public int Game_Id { get; set; }
        public string GameName { get; set; }
        public bool IsTrue { get; set; }
  }

 public class GameInfo1
 {   
        public bool Selected { get; set; }
        public int GameType_Id { get; set; }
        public string GameType { get; set; }
  }

Controller

 public class DefaultController : BaseController
    {
        GameEntities _dbContext = new GameEntities();

        public ActionResult Index()
        {
            GameUser1 user1 = new GameUser1();

            List info1 = (from a in _dbContext.GameInfoes
                                     select new GameInfo1
                                     {
                                         GameType_Id = a.GameType_Id,
                                         GameType = a.GameType
                                     }).ToList();
            user1.User_ID = 0;
            user1.GameTypeList = info1;
            user1.GameTypeId = 1;
            user1.GameList1 = new List();
            return View(user1);
        }

        [HttpPost]
        public ActionResult addEditUserDetail(GameUser1 model)
        {

            if (model.User_ID == 0)
            {
                var user1 = new UserGame()
                {
                    Fname = model.FName,
                    Email = model.Email,
                    Phoneno = model.Mobile,
                    GameType_Id = model.GameTypeId
                };
                _dbContext.UserGames.Add(user1);
                foreach (var item in model.GameSelected)
                {
                    var data1 = new GameUser()
                    {
                        User_ID = user1.User_ID,
                        Game_ID = item
                    };
                    _dbContext.GameUsers.Add(data1);
                }
            }
            else
            {
                try
                {
                    var user1 = _dbContext.UserGames.FirstOrDefault(x =&gt; x.User_ID == model.User_ID);
                    var user2 = new UserGame()
                    {
                        User_ID = model.User_ID,
                        Fname = model.FName,
                        Email = model.Email,
                        Phoneno = model.Mobile,
                        GameType_Id = model.GameTypeId
                    };
                    _dbContext.Entry(user1).CurrentValues.SetValues(user2);

                    List GameSelected = _dbContext.GameUsers.Where(p =&gt; p.User_ID == model.User_ID).Select(p =&gt; p.Game_ID).ToList(); ;


                    if (model.GameSelected != null)
                    {
                        foreach (var item in model.GameSelected)
                        {
                            if (!GameSelected.Contains(item))
                            {
                                var data2 = new GameUser()
                                {
                                    User_ID = user1.User_ID,
                                    Game_ID = item
                                };
                                _dbContext.GameUsers.Add(data2);
                            }
                        }

                        foreach (var item in GameSelected)
                        {
                            if (!model.GameSelected.Contains(item))
                            {
                                var data3 = _dbContext.GameUsers.FirstOrDefault(x =&gt; x.User_ID == model.User_ID &amp;&amp; x.Game_ID == item);
                                _dbContext.GameUsers.Remove(data3);
                            }
                        }
                    }
                    else
                    {
                        foreach (var item in GameSelected)
                        {
                            var data3 = _dbContext.GameUsers.FirstOrDefault(x =&gt; x.User_ID == model.User_ID &amp;&amp; x.Game_ID == item);
                            _dbContext.GameUsers.Remove(data3);
                        }
                    }
                    _dbContext.SaveChanges();
                }
                catch (Exception ex) { }
            }       
            var result = new { Success = "False", Message = "Error Message" };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult getGameList(string gameTypeId, string userId)
        {
            List gameLists1 = new List();
            List GameSelected = new List();
            try
            {
                if (userId != null &amp;&amp; userId != "")
                {
                    int userID = int.Parse(userId);
                    GameSelected = _dbContext.GameUsers.Where(p =&gt; p.User_ID == userID).Select(p =&gt; p.Game_ID).ToList();
                }
                int n = int.Parse(gameTypeId);
                gameLists1 = (from a in _dbContext.GameLists.Where(x =&gt; x.GameType_ID == n)
                              select new SelectListItem
                              {
                                  Value = a.Game_ID.ToString(),
                                  Text = a.GameName,
                                  Selected = GameSelected.Contains(a.Game_ID)
                              }).ToList();
            }
            catch (Exception ex) { }
            return PartialView("~/Views/Default/_partialGameList.cshtml", gameLists1);
        }

        public ActionResult loadUserGrid()
        {
            List userData1 = new List();
            List userData2 = new List();
            try
            {
                userData1 = _dbContext.UserGames.ToList();

                foreach (var item in userData1)
                {
                    List GameSelected = _dbContext.GameUsers.Where(p =&gt; p.User_ID == item.User_ID).Select(p =&gt; p.Game_ID).ToList();
                    List gameList = (_dbContext.GameLists.Where(x =&gt; GameSelected.Contains(x.Game_ID))).ToList();
                    var data = new GameUser1
                    {
                        User_ID = item.User_ID,
                        FName = item.Fname,
                        Email = item.Email,
                        Mobile = item.Phoneno,
                        GameList = string.Join(" , ", gameList.Select(x =&gt; x.GameName))
                    };
                    userData2.Add(data);
                }
            }
            catch (Exception ex) { }
            return Json(new { data = userData2 }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult getUserData(string id)
        {
            UserGame user = new UserGame();
            GameUser1 user1 = new GameUser1();

            try
            {
                int n = int.Parse(id);
                user = _dbContext.UserGames.FirstOrDefault(x =&gt; x.User_ID == n);

                List info1 = (from a in _dbContext.GameInfoes
                                         select new GameInfo1
                                         {
                                             GameType_Id = a.GameType_Id,
                                             GameType = a.GameType
                                         }).ToList();

                user1.User_ID = user.User_ID;
                user1.FName = user.Fname;
                user1.Mobile = user.Phoneno;
                user1.Email = user.Email;
                user1.GameTypeList = info1;
                user1.GameTypeId = user.GameType_Id;
                //     user1.GameList1 = new List();

                user1.GameSelected = _dbContext.GameUsers.Where(p =&gt; p.User_ID == user.User_ID).Select(p =&gt; p.Game_ID).ToList();
                List gameLists1 = new List();
                gameLists1 = (from a in _dbContext.GameLists.Where(x =&gt; x.GameType_ID == user.GameType_Id)
                              select new SelectListItem
                              {
                                  Value = a.Game_ID.ToString(),
                                  Text = a.GameName,
                                  Selected = user1.GameSelected.Contains(a.Game_ID)
                              }).ToList();

                user1.GameList1 = gameLists1;
            }
            catch (Exception ex) { }
            return PartialView("_partialUserAdd", user1);
        }

        public ActionResult deleteUserDetails(string userId)
        {
            try
            {
                int userID = int.Parse(userId);
                var user1 = _dbContext.UserGames.FirstOrDefault(x =&gt; x.User_ID == userID);
                _dbContext.UserGames.Remove(user1);
                _dbContext.SaveChanges();
            }
            catch(Exception ex) { }
            return Json("Success", JsonRequestBehavior.AllowGet);
        }
    }

Views

Index.cshtml         


@using ManekTech1.Controllers
@model ManekTech1.Models.GameUser1
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>

    <link href="~/assets/css/bootstrap.min.css" rel="stylesheet" />
    <script src="~/Scripts/bootstrap.js"></script>
 
    <script src="~/Scripts/jquery.form.js"></script>
 
    <link href="~/assets/css/icons.css" rel="stylesheet" />
    <link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css" rel="stylesheet" />

    <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js "></script>


    <link href="~/Scripts/SweetAlert/sweetalert.css" rel="stylesheet" />
    <script src="~/Scripts/SweetAlert/sweetalert.min.js"></script>

    <script src="~/Scripts/jquery.growl.js"></script> 
    <link href="~/Content/jquery.growl.css" rel="stylesheet" />
</head>
<body>
    <div>
        <div class="container">
            <div id="addModalUser">
                @if (Model == null)
                {
                    Html.RenderPartial("_partialUserAdd", new ManekTech1.Models.GameUser1());
                }
                else
                {
                    Html.RenderPartial("_partialUserAdd", Model);
                }
            </div>
        </div>
        <div class="row" style="background-color:#f5f5f5;margin-bottom:5px;">
            &nbsp;
        </div>
        <div class="container">
            <div id="UserGrid">
                @Html.Partial("_partialUserGrid")
            </div>
        </div>
    </div>
</body>
</html>

_partialUserAdd.cshtml

@model ManekTech1.Models.GameUser1


@using (Html.BeginForm("addEditUserDetail", "Default", FormMethod.Post, new { @id = "frm_User_Modal", @ReturnUrl = ViewBag.ReturnUrl }))
{
    @Html.HiddenFor(m => m.User_ID)
    <h2>Game User Form</h2>
    <div class="panel panel-default">
        <div class="panel-body">
            <div class="row">
                <div class="col-sm-12">
                    <label for="">Name</label>
                    @Html.TextBoxFor(model => model.FName, new { @class = "form-control", @placeholder = "Enter.." })
                    @Html.ValidationMessageFor(m => m.FName, "", new { @class = "text-danger" })
                </div>
                <div class="col-sm-12">
                    <label for="">PhoneNo</label>
                    @Html.TextBoxFor(model => model.Mobile, new { @class = "form-control", @placeholder = "Enter.." })
                    @Html.ValidationMessageFor(m => m.Mobile, "", new { @class = "text-danger" })
                </div>
                <div class="col-sm-12">
                    <label for="">Email</label>
                    @Html.TextBoxFor(model => model.Email, new { @class = "form-control", @placeholder = "Enter.." })
                    @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
                </div>
                <div class="col-sm-12">
                    <label for="">Game Type</label>
                    @Html.DropDownListFor(model => model.GameTypeId, new SelectList(Model.GameTypeList, "GameType_Id", "GameType", 0), new { @class = "form-control", @Id = "ddlGameType" })
                </div>
                <div class="col-sm-12">
                    <div class="col-sm-4">
                    </div>
                    <div class="col-sm-4">
                        <div id="displayGameList" style="display:none">
                            @Html.Partial("_partialGameList", Model.GameList1)
                        </div>
                    </div>
                </div>
                <div class="col-sm-12">
                    <div class="form-group text-right m-b-0">
                        <button class="btn btn-primary waves-effect waves-light" type="submit" id="btnsubmit">
                            Submit
                        </button>
                        <button type="reset" class="btn btn-default waves-effect waves-light m-l-5" onClick="window.location.reload();">
                            Cancel
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
}
<script>
    $(function () {
        $('#frm_User_Modal').ajaxForm({
            beforeSubmit: ShowRequestAddress,
            success: SubmitSuccesfulPoints,
            error: AjaxErrorAddress
        });
    });
    function ShowRequestAddress(formData, jqForm, options) { }

    function AjaxErrorAddress() { }

    function SubmitSuccesfulPoints(result, statusText) {
        $.growl.notice({ title: "Success", message: "User Saved Successfully" });
        $('#userTable').DataTable().ajax.reload();
        clearAllFields();
    }

    function clearAllFields() {
        $('#User_ID').val('');
        $('#FName').val('');
        $('#Mobile').val('');
        $('#Email').val('');
        $('input:checkbox').removeAttr('checked');

        var op1 = $("#btnsubmit").html();
        if (op1 == "Update")
            $("#btnsubmit").html('Submit');

    }
</script>

<script>
    $(function () {
        $("#ddlGameType").change(function () {
            var userId = $('#User_ID').val();
            var gameTypeId = $('option:selected', this).val();

            alert("hiii");
            $.get('@Url.Action("getGameList", "Default")?gameTypeId=' + gameTypeId + '&userId=' + userId, function (data) {
                $('#displayGameList').html(data);
            });
            $("#displayGameList").show();
        });
    });

    $(function () {
        var userId = $('#User_ID').val();
        if (userId == "0") {
            var data1 = $('#ddlGameType').val();
            $.get('@Url.Action("getGameList", "Default")?gameTypeId=' + data1 + '', function (data) {
                $('#displayGameList').html(data);
            });
            $("#displayGameList").show();
        }
    });
</script>

_partialUserGrid.cshtml

<div class="panel panel-default">
    <div class="panel-body">
        <div class="card-box table-responsive">
            <h4 class="m-t-0 header-title"><b>User List</b></h4>
            <table id="userTable" class="table table-bordered"></table>
        </div>
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function () {
        BindUserTable();
    });

    function BindUserTable() {
        if ($.fn.DataTable.isDataTable("#userTable")) {
            $('#userTable').dataTable().fnDestroy();
            $('#userTable').html('<table cellspacing="0" class="table grid table-hover table-bordered" width="100%"  id="userTable"></table>');
        }

        $("#userTable").DataTable({
            "ajax": {
                "url": '@Url.Action("loadUserGrid", "Default")',
                "type": "GET",
                "datatype": "json"
            },
            "columns": [
                { "title": "UserId", "data": "User_ID", "autoWidth": true },
                { "title": "Name", "data": "FName", "autoWidth": true },
                { "title": "Email", "data": "Email", "autoWidth": true },
                { "title": "Game", "data": "GameList", "autoWidth": true },
                {
                    "title": "Action",
                    "data": "User_ID",
                    "searchable": false,
                    "sortable": false,
                    "render": function (data, type, full, meta) {
                        return '<a href="#" onclick="editUserData(\'' + data + '\')" class="btn-sm btn-icon waves-effect waves-light btn-success m-b-5" title="Edit"> <i class="fa fa-edit fa-lg"></i> </a>&nbsp; '
                            + '<a href="#" onclick="myfunction(\'' + data + '\')" class="btn-sm btn-icon waves-effect waves-light btn-danger m-b-5" title="Delete"> <i class="fa fa-remove fa-lg"></i> </a>';
                    }
                }
            ],
            "columnDefs": [
                { "width": "10%", "targets": 4 },
            ],

        });

        $('#userTable tbody').on('click', 'tr', function () {
            $('#userTable tr').removeClass('highlighted');
            $(this).addClass('highlighted');
        });
    }

    function myfunction(id1) {
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this Record!",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes, delete it!",
            cancelButtonText: "No, cancel plx!",
            closeOnConfirm: false,
            closeOnCancel: false
        },
            function (isConfirm) {
                if (isConfirm) {
                    $.post('@Url.Action("deleteUserDetails", "Default")', { userId: id1, }, function (data) { });
                    swal("Deleted!", "Your imaginary file has been deleted.", "success");
                    $('#userTable').DataTable().ajax.reload();
                } else {
                    swal("Cancelled", "Your Record is safe ", "error");
                }
            });
    }

    function editUserData(id1) {
        $.get('@Url.Action("getUserData", "Default")?id=' + id1 + '', function (data) {
            $('#addModalUser').html(data);
            $("#btnsubmit").html('Update');
            $("#displayGameList").show();
        });
    }
</script>

_partialGameList.cshtml

@model List<SelectListItem>
@{
    int n = Model.Count;
    int i = 0;
}
<div class="row">
    <h4>Select Game</h4>
    <table class="table m-0">     

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @item.Text
                </td>
                <td>
                    <input type="checkbox" id="@item.Value" name="GameSelected" value="@item.Value" @(item.Selected ? "checked" : "") />
                </td>             
            </tr>
        }
    </table>
</div>

Database

CREATE TABLE [dbo].[GameInfo](
[GameType_Id] [int] IDENTITY(1,1) NOT NULL,
[GameType] [nvarchar](50) NULL
)
CREATE TABLE [dbo].[GameList](
[Game_ID] [int] IDENTITY(1,1) NOT NULL,
[GameType_ID] [int] NOT NULL,
[GameName] [nvarchar](50) NULL
)
CREATE TABLE [dbo].[GameUser](
[GameUser_ID] [int] IDENTITY(1,1) NOT NULL,
[User_ID] [int] NOT NULL,
[Game_ID] [int] NOT NULL
)
CREATE TABLE [dbo].[UserGame](
[User_ID] [int] IDENTITY(1,1) NOT NULL,
[Fname] [nvarchar](50) NULL,
[Email] [nvarchar](50) NULL,
[Phoneno] [nvarchar](50) NULL,
[GameType_Id] [int] NOT NULL
)
INSERT [dbo].[GameInfo] ([GameType_Id], [GameType]) VALUES (1, N'InDoor')
INSERT [dbo].[GameInfo] ([GameType_Id], [GameType]) VALUES (2, N'OutDoor')

INSERT [dbo].[GameList] ([Game_ID], [GameType_ID], [GameName]) VALUES (1, 1, N'TableTennis')
INSERT [dbo].[GameList] ([Game_ID], [GameType_ID], [GameName]) VALUES (2, 1, N'Carom')
INSERT [dbo].[GameList] ([Game_ID], [GameType_ID], [GameName]) VALUES (3, 2, N'Hockey')
INSERT [dbo].[GameList] ([Game_ID], [GameType_ID], [GameName]) VALUES (4, 2, N'Cricket')

INSERT [dbo].[GameUser] ([GameUser_ID], [User_ID], [Game_ID]) VALUES (3, 3, 1)
INSERT [dbo].[GameUser] ([GameUser_ID], [User_ID], [Game_ID]) VALUES (7, 5, 3)
INSERT [dbo].[GameUser] ([GameUser_ID], [User_ID], [Game_ID]) VALUES (8, 5, 4)

INSERT [dbo].[UserGame] ([User_ID], [Fname], [Email], [Phoneno], [GameType_Id]) VALUES (3, N'keshav', N'keshav@akdm.com', N'1111111', 1)
INSERT [dbo].[UserGame] ([User_ID], [Fname], [Email], [Phoneno], [GameType_Id]) VALUES (5, N'Amit', N'amitmech@gmail.com', N'1112222', 2)

Image Gallery - Image Add/Delete/Preview - Single Page App -

https://github.com/TheKalin/jQuery-File-Upload.MVC5 Helper Class / Models   public class FilesHelperDB     {         dbImageGallery...