Saturday, March 18, 2017

Part 37 - Implementing search functionality using jquery and partial view in Asp.net mvc



#Expected Output 





#Controller Code(TestController.cs)


using MVCTutorial.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace MVCTutorial.Controllers
{
    public class TestController : Controller
    {

        public ActionResult Index()
        {
            MVCTutorialEntities db = new MVCTutorialEntities();

            List<EmployeeViewModel> list = db.Employees.Select(x => new EmployeeViewModel { Name = x.Name, EmployeeId = x.EmployeeId, DepartmentName = x.Department.DepartmentName, Address = x.Address }).ToList();

            ViewBag.EmployeeList = list;

            return View();
        }

        public ActionResult GetSearchRecord(string SearchText)
        {

            MVCTutorialEntities db = new MVCTutorialEntities();


            List<EmployeeViewModel> list = db.Employees.Where(x => x.Name.Contains(SearchText) || x.Department.DepartmentName.Contains(SearchText)).Select(x => new EmployeeViewModel { Name = x.Name, EmployeeId = x.EmployeeId, DepartmentName = x.Department.DepartmentName, Address = x.Address }).ToList();

            return PartialView("SearchPartial", list);


        }

    }
}

  
#Model (EmployeeViewModel.cs) 


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MVCTutorial.Models
{
    public class EmployeeViewModel
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public Nullable<int> DepartmentId { get; set; }
        public string Address { get; set; }
        public Nullable<bool> IsDeleted { get; set; }
        //Extra attribute
        public string DepartmentName { get; set; }
        public bool Remember { get; set; }
        public string SiteName { get; set; }
       
    }
}

 # View (Index.cshtml)


@model MVCTutorial.Models.EmployeeViewModel
@{
    ViewBag.Title = "Index";
    // Layout = null;
}

<div class="panel panel-body" style="min-height:256px">

    <div class="col-md-3">

        @*@{ Html.RenderAction("SideMenu", "Test");}*@

    </div>
    <div class="col-md-9">
        @Html.TextBoxFor(m => m.Name, new { @class="form-control",@placeholder="Search here"})
        <img src="~/Content/loading.gif" id="loader" height="20" width="20" style="display:none"/>

        <table class="table table-striped">
            <tr>
                <th>
                    Name
                </th>
                <th>
                    DepartmentName
                </th>
                <th>
                    Address
                </th>
                <th>
                    Action
                </th>
            </tr>
            <tbody id="employeeRow">

                @if (ViewBag.EmployeeList != null)
                {
                    foreach (var item in ViewBag.EmployeeList)
                    {
                        <tr>
                            <td>@item.Name</td>
                            <td>@item.DepartmentName</td>
                            <td>@item.Address</td>
                            <td><a href="#"><i class="glyphicon glyphicon-eye-open"></i>View</a></td>
                        </tr>

                    }

                }

            </tbody>
        </table>

    </div>

</div>

<script>

    $(document).ready(function () {

        $("#Name").keydown(function () {
            $("#loader").show();
            var searchtext = $(this).val();
            debugger
            $.ajax({

                type: "Post",
                url: "/Test/GetSearchRecord?SearchText=" + searchtext,
                contentType: "html",
                success: function (response) {                   
                    $("#loader").hide();

                    $("#employeeRow").html(response);

                }

            })

        })

    })

</script>

 # Partial View (SearchPartial.cshtml)


@model IEnumerable<MVCTutorial.Models.EmployeeViewModel>

@if (Model != null)
{
    foreach (var item in Model)
    {
        <tr>
            <td>@item.Name</td>
            <td>@item.DepartmentName</td>
            <td>@item.Address</td>
            <td><a href="#"><i class="glyphicon glyphicon-eye-open"></i>View</a></td>
        </tr>

    }
}

 #Database Script (MVCTutorial > Employee Table ) 


USE [MVCTutorial]
GO
/****** Object:  Table [dbo].[Employee]    Script Date: 19-03-2017 00:02:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employee](
 [EmployeeId] [int] IDENTITY(1,1) NOT NULL,
 [Name] [varchar](50) NULL,
 [DepartmentId] [int] NULL,
 [Address] [varchar](150) NULL,
 [IsDeleted] [bit] NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
 [EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Employee]  WITH CHECK ADD  CONSTRAINT [FK_Employee_Department] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Department] ([DepartmentId])
GO
ALTER TABLE [dbo].[Employee] CHECK CONSTRAINT [FK_Employee_Department]
GO

 

All Code Factory

Monday, March 13, 2017

Part 36 - Cascading dropdown list using Jquery and Partial View in Asp.net MVC



#Expected Output 



#Controller Code(TestController.cs)


using MVCTutorial.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace MVCTutorial.Controllers
{
    public class TestController : Controller
    {

        public ActionResult Index()
        {

            ViewBag.CountryList = new SelectList(GetCountryList(),"CountryId","CountryName");

            return View();
        }

     
        public List<Country> GetCountryList()
        {

            MVCTutorialEntities db = new MVCTutorialEntities();

            List<Country> countries = db.Countries.ToList();

            return countries;


        }

        public ActionResult GetStateList(int CountryId)
        {
            MVCTutorialEntities db = new MVCTutorialEntities();

            List<State> stateList = db.States.Where(x => x.CountryId == CountryId).ToList();

            ViewBag.StateOptions = new SelectList(stateList, "StateId", "StateName");

            return PartialView("StateOptionPartial");

        }

    }
}

  
#Model (CountryAndStateVM.cs) 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCTutorial.Models
{
    public class CountryAndStateVM
    {
        public int CountryId { get; set; }
        public int StateId { get; set; }

    }
}

 # View (Index.cshtml)


@model MVCTutorial.Models.CountryAndStateVM
@{
    ViewBag.Title = "Index";
    // Layout = null;
}

<div class="panel panel-body" style="min-height:256px">

    @*<div class="col-md-3">

        @{ Html.RenderAction("SideMenu", "Test");}

    </div>*@
    <div class="col-md-9">

        @if (ViewBag.CountryList != null)
        { 
         @Html.DropDownListFor(m => m.CountryId, ViewBag.CountryList as SelectList, "-- Select Country--", new { @class="form-control"})
         
        }
        @Html.DropDownListFor(m => m.StateId, new SelectList(""), "--Select State--", new { @class = "form-control" })


    </div>

</div>

<script>

    $(document).ready(function () {

        $("#CountryId").change(function () {

            var countryId = $(this).val();
            debugger
            $.ajax({

                type: "Post",
                url: "/Test/GetStateList?CountryId=" + countryId,
                contentType:"html",
                success: function (response) {
                  debugger
                    $("#StateId").empty();
                    $("#StateId").append(response);

                }

            })

        })

    })

</script>

 # Partial View (StateOptionPartial.cshtml)


<option value="">--Select State--</option>
@if (ViewBag.StateOptions != null)
{
    
    foreach (var item in ViewBag.StateOptions) { 
    
      <option value="@item.Value">@item.Text </option>
    
    }

}


 #Database Script (MVCTutorial) 


USE [MVCTutorial]
GO
/****** Object:  Table [dbo].[Country]    Script Date: 13-03-2017 17:06:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Country](
 [CountryId] [int] IDENTITY(1,1) NOT NULL,
 [CountryName] [varchar](100) NULL,
 CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED 
(
 [CountryId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[State]    Script Date: 13-03-2017 17:07:00 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[State](
 [StateId] [int] IDENTITY(1,1) NOT NULL,
 [StateName] [varchar](100) NULL,
 [CountryId] [int] NULL,
 CONSTRAINT [PK_State] PRIMARY KEY CLUSTERED 
(
 [StateId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Country] ON 

GO
INSERT [dbo].[Country] ([CountryId], [CountryName]) VALUES (1, N'India')
GO
INSERT [dbo].[Country] ([CountryId], [CountryName]) VALUES (2, N'United States')
GO
SET IDENTITY_INSERT [dbo].[Country] OFF
GO
SET IDENTITY_INSERT [dbo].[State] ON 

GO
INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (1, N'Delhi', 1)
GO
INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (2, N'Uttar Pradesh', 1)
GO
INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (3, N'Punjab', 1)
GO
INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (4, N'Haryana', 1)
GO
INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (5, N'Bihar', 1)
GO
INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (7, N'California', 2)
GO
INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (8, N'Texas', 2)
GO
INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (9, N'New York', 2)
GO
INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (10, N'Michigan', 2)
GO
INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (11, N'Virginia', 2)
GO
INSERT [dbo].[State] ([StateId], [StateName], [CountryId]) VALUES (12, N'New Jersey', 2)
GO
SET IDENTITY_INSERT [dbo].[State] OFF
GO
ALTER TABLE [dbo].[State]  WITH CHECK ADD  CONSTRAINT [FK_State_Country] FOREIGN KEY([CountryId])
REFERENCES [dbo].[Country] ([CountryId])
GO
ALTER TABLE [dbo].[State] CHECK CONSTRAINT [FK_State_Country]
GO

   

All Code Factory

Sunday, March 12, 2017

Part 35 - Download image from URL and save to SQL Server using Jquery in Asp.net MVC




#Expected Output 



#Controller Code(TestController.cs)


using MVCTutorial.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace MVCTutorial.Controllers
{
    public class TestController : Controller
    {

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

        public ActionResult SideMenu()
        {

            return PartialView("SideMenu");

        }
        public JsonResult ImageUpload(ProductViewModel model)
        {

            MVCTutorialEntities db = new MVCTutorialEntities();
            int imageId = 0;

            var file = model.ImageFile;

            byte[] imagebyte = null;

            if (file != null)
            {

                file.SaveAs(Server.MapPath("/UploadedImage/" + file.FileName));

                BinaryReader reader = new BinaryReader(file.InputStream);

                imagebyte = reader.ReadBytes(file.ContentLength);

                ImageStore img = new ImageStore();

                img.ImageName = file.FileName;
                img.ImageByte = imagebyte;
                img.ImagePath = "/UploadedImage/" + file.FileName;
                img.IsDeleted = false;
                db.ImageStores.Add(img);
                db.SaveChanges();

                imageId = img.ImageId;

            }

            if (model.ImageUrl != null)
            {

                imagebyte = DownloadImage(model.ImageUrl);
               
                ImageStore img = new ImageStore();

                img.ImageName = "Abc"; //file.FileName;
                img.ImageByte = imagebyte;
                img.ImagePath = model.ImageUrl;
                img.IsDeleted = false;
                db.ImageStores.Add(img);
                db.SaveChanges();

                imageId = img.ImageId;

            }

            return Json(imageId, JsonRequestBehavior.AllowGet);

        }

        public ActionResult ImageRetrieve(int imgID)
        {
            MVCTutorialEntities db = new MVCTutorialEntities();

            var img = db.ImageStores.SingleOrDefault(x => x.ImageId == imgID);

            return File(img.ImageByte, "image/jpg");


        }

        public byte[] DownloadImage(string Url)
        {
            var webclient = new WebClient();

            byte[] imagebytes = webclient.DownloadData(Url);

            return imagebytes;

        }


    }
}

  
#Model (ProductViewModel.cs) 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCTutorial.Models
{
    public class ProductViewModel
    {
        public string ProductName { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public Nullable<int> Price { get; set; }
        public Nullable<int> ImageId { get; set; }
        public HttpPostedFileWrapper ImageFile { get; set; }
        public string ImageUrl { get; set; }
        
    }
}

 # View (Index.cshtml)


@model MVCTutorial.Models.ProductViewModel
@{
    ViewBag.Title = "Index";
    // Layout = null;
}

<div class="panel panel-body" style="min-height:256px">

    @*<div class="col-md-3">

        @{ Html.RenderAction("SideMenu", "Test");}

    </div>*@
    <div class="col-md-9">

        <div class="col-md-4">
            <div class="btn btn-primary">
                <input type="file" id="imageBrowes" />
            </div>
            <hr />

            <div id="imgPreview" class="thumbnail" style="display:none">
                <img class="img-responsive" id="targetImg" />
                <div class="caption">
                    <a href="#" onclick="ClearPreview()"><i class="glyphicon glyphicon-trash"></i></a>
                    <span id="description"></span>
                </div>
                <a href="#" class="btn btn-default" onclick="Uploadimage()">Upload</a>
            </div>
            <input type="text" class="form-control" id="url" />
            <a href="#" class="btn btn-primary btn-block" onclick="Uploadimage()"> Save Image by URL</a>
        </div>

 
       <div class="col-md-2 thumbnail" id="uploadedImage" >

           <img src="~/Content/loading.gif" height="20" width="20" style="display:none" id="loader"/>
       </div>
    </div>

    



</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>

    $(document).ready(function () {

        $("#imageBrowes").change(function () {



            var File = this.files;

            if (File && File[0]) {
                ReadImage(File[0]);
            }

        })


    })


    var ReadImage = function (file) {

        var reader = new FileReader;
        var image = new Image;

        reader.readAsDataURL(file);
        reader.onload = function (_file) {

            image.src = _file.target.result;
            image.onload = function () {

                var height = this.height;
                var width = this.width;
                var type = file.type;
                var size = ~~(file.size / 1024) + "KB";

                $("#targetImg").attr('src', _file.target.result);
                $("#description").text("Size:" + size + ", " + height + "X " + width + ", " + type + "");
                $("#imgPreview").show();

            }

        }

    }

    var ClearPreview = function () {
        $("#imageBrowes").val('');
        $("#description").text('');
        $("#imgPreview").hide();

    }

    var Uploadimage = function () {
     
        $("#loader").show();
        var file = $("#imageBrowes").get(0).files;
        var url = $("#url").val();

        var data = new FormData;
        data.append("ImageFile", file[0]);
        data.append("ProductName", "SamsungA8");
        data.append("ImageUrl", url);

        $.ajax({

            type: "Post",
            url: "/Test/ImageUpload",
            data: data,
            contentType: false,
            processData: false,
            success: function (imgID) {
                $("#loader").hide();

                ClearPreview();

                $("#uploadedImage").append('<img src="/Test/ImageRetrieve?imgID=' + imgID + '" class="img-responsive thumbnail"/>');


                //$("#uploadedImage").append('<img src="/UploadedImage/' + response + '" class="img-responsive thumbnail"/>');


            }

        })

        
        //
    }

</script>

 # Layout (_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")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/Test/Index">
                    <img alt="Brand" src="~/Content/Images/logo.png" height="20" width="20">
                </a>
            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li><a href="#"><span class="glyphicon glyphicon-home"></span></a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Services <span class="caret"></span></a>
                        <ul class="dropdown-menu" role="menu" id="myTab">
                            <li role="presentation"><a href="#music" aria-controls="music" role="tab" data-toggle="tab"><span class="glyphicon glyphicon-music"> </span> Music & Dance</a></li>
                            <li class="divider"></li>
                            <li role="presentation"><a href="#training" aria-controls="training" role="tab" data-toggle="tab"><span class="glyphicon glyphicon-book"> </span> Summar Training</a></li>
                            <li class="divider"></li>
                            <li role="presentation"><a href="#website" aria-controls="website" role="tab" data-toggle="tab"><span class="glyphicon glyphicon-cloud"> </span> Website Building</a></li>
                        </ul>

                    </li>
                    <li><a href="#">About Us</a></li>
                    <li><a href="#">Career</a></li>
                </ul>
                <form class="navbar-form navbar-left" role="search">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Search">
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>

                @if (Session["UserId"] != null) { 
                
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#">Welcome :@Session["UserName"]  </a></li>
                    <li><a href="/Test/Logout">Logout</a></li>

                </ul>
                
                }
                else { 
                 <ul class="nav navbar-nav navbar-right">
                    <li><a href="/Test/Login">Login</a></li>
                    <li><a href="/Test/Registration">Register</a></li>

                </ul>

                }
               
                }

            </div>
        </div>

    </nav>

    <div class="panel-body" style="min-height:450px">

        @RenderBody()


    </div>

    <div class="well" style="background-color:#000000;color:wheat;margin-bottom:0px">

        <div class="col-lg-4" style="margin-left:20px">

            <h3><span class="glyphicon glyphicon-map-marker"></span> Address</h3>
            <ul class="list-group list-unstyled">

                <li>Technotips Ltd.</li>
                <li>xyz Industrial Area</li>
                <li>Phase-2,New Delhi-52</li>
            </ul>
        </div>

        <div class="col-lg-4">

            <h3><span class="glyphicon glyphicon-cog"></span> Our Services</h3>
            <ul class="list-group list-unstyled">

                <li><span class="glyphicon glyphicon-music"></span> <a href="#">Musical & Dance Traning</a> </li>
                <li><span class="glyphicon glyphicon-book"></span>    <a href="#">Training in Asp.Net,Java,android etc.</a></li>
                <li><span class="glyphicon glyphicon-globe"></span> <a href="#">Web designing -corporate & Domestic</a> </li>

            </ul>
        </div>

        <div class="col-lg-3">

            <h3><span class="glyphicon glyphicon-briefcase"></span> Career</h3>
            <ul class="list-group list-unstyled">

                <li><span class="glyphicon glyphicon-music"></span> <a href="#">Musical & Dance</a> </li>
                <li><span class="glyphicon glyphicon-book"></span>  <a href="#">Summar training</a></li>
                <li><span class="glyphicon glyphicon-globe"></span>    <a href="#">Website Designing</a></li>

            </ul>
        </div>

        <div style="clear:both"></div>


    </div>


    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

    @RenderSection("scripts", required: false)


</body>
</html>


 #Database Script (MVCTutorial) 


USE [MVCTutorial]
GO
/****** Object:  Table [dbo].[ImageStore]    Script Date: 12-03-2017 00:16:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ImageStore](
 [ImageId] [int] IDENTITY(1,1) NOT NULL,
 [ImageName] [nvarchar](1000) NULL,
 [ImageByte] [image] NULL,
 [ImagePath] [nvarchar](1000) NULL,
 [IsDeleted] [bit] NULL,
 CONSTRAINT [PK_ImageStore] PRIMARY KEY CLUSTERED 
(
 [ImageId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Product]    Script Date: 12-03-2017 00:16:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Product](
 [ProductId] [int] IDENTITY(1,1) NOT NULL,
 [Title] [nvarchar](200) NULL,
 [Description] [nvarchar](1000) NULL,
 [Price] [int] NULL,
 [ImageId] [int] NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED 
(
 [ProductId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
ALTER TABLE [dbo].[Product]  WITH CHECK ADD  CONSTRAINT [FK_Product_ImageStore] FOREIGN KEY([ImageId])
REFERENCES [dbo].[ImageStore] ([ImageId])
GO
ALTER TABLE [dbo].[Product] CHECK CONSTRAINT [FK_Product_ImageStore]
GO

   

All Code Factory

Saturday, March 11, 2017

Part 34 - Upload image to SQL server and retrieve using JQuery in Asp.net MVC | To SQL server




#Expected Output 



#Controller Code(TestController.cs)


using MVCTutorial.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace MVCTutorial.Controllers
{
    public class TestController : Controller
    {

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


        public JsonResult ImageUpload(ProductViewModel model) {
            
            MVCTutorialEntities db = new MVCTutorialEntities();
            int imageId=0;

            var file = model.ImageFile;

            byte[] imagebyte = null;

            if (file != null) {
                               
                file.SaveAs(Server.MapPath("/UploadedImage/" + file.FileName));

                BinaryReader reader = new BinaryReader(file.InputStream);

                imagebyte = reader.ReadBytes(file.ContentLength);

                ImageStore img = new ImageStore();

                img.ImageName = file.FileName;
                img.ImageByte = imagebyte;
                img.ImagePath = "/UploadedImage/" + file.FileName;
                img.IsDeleted = false;
                db.ImageStores.Add(img);
                db.SaveChanges();

                imageId = img.ImageId;
 
            }

            return Json(imageId, JsonRequestBehavior.AllowGet);
        
        }

        public ActionResult ImageRetrieve(int imgID)
        {
            MVCTutorialEntities db = new MVCTutorialEntities();

            var img = db.ImageStores.SingleOrDefault(x => x.ImageId == imgID);

            return File(img.ImageByte, "image/jpg");
                        
        
        }
    }
}

  
#Model (ProductViewModel.cs) 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCTutorial.Models
{
    public class ProductViewModel
    {
        public string ProductName { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public Nullable<int> Price { get; set; }
        public Nullable<int> ImageId { get; set; }
        public HttpPostedFileWrapper ImageFile { get; set; }
    }
}

 # View (Index.cshtml)


@model MVCTutorial.Models.ProductViewModel
@{
    ViewBag.Title = "Index";
    // Layout = null;
}

<div class="panel panel-body" style="min-height:256px">

    @*<div class="col-md-3">

        @{ Html.RenderAction("SideMenu", "Test");}

    </div>*@
    <div class="col-md-9">


        <div class="col-md-4">
           
            <div class="btn btn-primary">
                <input type="file" id="imageBrowes" />
            </div>
            <hr />

            <div id="imgPreview" class="thumbnail" style="display:none">
                <img class="img-responsive" id="targetImg" />
                <div class="caption">
                    <a href="#" onclick="ClearPreview()"><i class="glyphicon glyphicon-trash"></i></a>
                    <span id="description"></span>
                </div>
                <a href="#" class="btn btn-default" onclick="Uploadimage()">Upload</a>
            </div>

        </div>
       <div class="col-md-2 thumbnail" id="uploadedImage" >


       </div>
    </div>

    



</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>

    $(document).ready(function () {

        $("#imageBrowes").change(function () {



            var File = this.files;

            if (File && File[0]) {
                ReadImage(File[0]);
            }

        })


    })


    var ReadImage = function (file) {

        var reader = new FileReader;
        var image = new Image;

        reader.readAsDataURL(file);
        reader.onload = function (_file) {

            image.src = _file.target.result;
            image.onload = function () {

                var height = this.height;
                var width = this.width;
                var type = file.type;
                var size = ~~(file.size / 1024) + "KB";

                $("#targetImg").attr('src', _file.target.result);
                $("#description").text("Size:" + size + ", " + height + "X " + width + ", " + type + "");
                $("#imgPreview").show();

            }

        }

    }

    var ClearPreview = function () {
        $("#imageBrowes").val('');
        $("#description").text('');
        $("#imgPreview").hide();

    }

    var Uploadimage = function () {
     
        var file = $("#imageBrowes").get(0).files;
         
        var data = new FormData;
        data.append("ImageFile", file[0]);
        data.append("ProductName", "SamsungA8");

        $.ajax({

            type: "Post",
            url: "/Test/ImageUpload",
            data: data,
            contentType: false,
            processData: false,
            success: function (imgID) {

                ClearPreview();

                $("#uploadedImage").append('<img src="/Test/ImageRetrieve?imgID=' + imgID + '" class="img-responsive thumbnail"/>');


                //$("#uploadedImage").append('<img src="/UploadedImage/' + response + '" class="img-responsive thumbnail"/>');


            }

        })

        
        //
    }

</script>

 # Layout (_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")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/Test/Index">
                    <img alt="Brand" src="~/Content/Images/logo.png" height="20" width="20">
                </a>
            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li><a href="#"><span class="glyphicon glyphicon-home"></span></a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Services <span class="caret"></span></a>
                        <ul class="dropdown-menu" role="menu" id="myTab">
                            <li role="presentation"><a href="#music" aria-controls="music" role="tab" data-toggle="tab"><span class="glyphicon glyphicon-music"> </span> Music & Dance</a></li>
                            <li class="divider"></li>
                            <li role="presentation"><a href="#training" aria-controls="training" role="tab" data-toggle="tab"><span class="glyphicon glyphicon-book"> </span> Summar Training</a></li>
                            <li class="divider"></li>
                            <li role="presentation"><a href="#website" aria-controls="website" role="tab" data-toggle="tab"><span class="glyphicon glyphicon-cloud"> </span> Website Building</a></li>
                        </ul>

                    </li>
                    <li><a href="#">About Us</a></li>
                    <li><a href="#">Career</a></li>
                </ul>
                <form class="navbar-form navbar-left" role="search">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Search">
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>

                @if (Session["UserId"] != null) { 
                
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#">Welcome :@Session["UserName"]  </a></li>
                    <li><a href="/Test/Logout">Logout</a></li>

                </ul>
                
                }
                else { 
                 <ul class="nav navbar-nav navbar-right">
                    <li><a href="/Test/Login">Login</a></li>
                    <li><a href="/Test/Registration">Register</a></li>

                </ul>

                }
               
                }

            </div>
        </div>

    </nav>

    <div class="panel-body" style="min-height:450px">

        @RenderBody()


    </div>

    <div class="well" style="background-color:#000000;color:wheat;margin-bottom:0px">

        <div class="col-lg-4" style="margin-left:20px">

            <h3><span class="glyphicon glyphicon-map-marker"></span> Address</h3>
            <ul class="list-group list-unstyled">

                <li>Technotips Ltd.</li>
                <li>xyz Industrial Area</li>
                <li>Phase-2,New Delhi-52</li>
            </ul>
        </div>

        <div class="col-lg-4">

            <h3><span class="glyphicon glyphicon-cog"></span> Our Services</h3>
            <ul class="list-group list-unstyled">

                <li><span class="glyphicon glyphicon-music"></span> <a href="#">Musical & Dance Traning</a> </li>
                <li><span class="glyphicon glyphicon-book"></span>    <a href="#">Training in Asp.Net,Java,android etc.</a></li>
                <li><span class="glyphicon glyphicon-globe"></span> <a href="#">Web designing -corporate & Domestic</a> </li>

            </ul>
        </div>

        <div class="col-lg-3">

            <h3><span class="glyphicon glyphicon-briefcase"></span> Career</h3>
            <ul class="list-group list-unstyled">

                <li><span class="glyphicon glyphicon-music"></span> <a href="#">Musical & Dance</a> </li>
                <li><span class="glyphicon glyphicon-book"></span>  <a href="#">Summar training</a></li>
                <li><span class="glyphicon glyphicon-globe"></span>    <a href="#">Website Designing</a></li>

            </ul>
        </div>

        <div style="clear:both"></div>


    </div>


    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

    @RenderSection("scripts", required: false)


</body>
</html>


 #Database Script (MVCTutorial) 


USE [MVCTutorial]
GO
/****** Object:  Table [dbo].[ImageStore]    Script Date: 12-03-2017 00:16:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ImageStore](
 [ImageId] [int] IDENTITY(1,1) NOT NULL,
 [ImageName] [nvarchar](1000) NULL,
 [ImageByte] [image] NULL,
 [ImagePath] [nvarchar](1000) NULL,
 [IsDeleted] [bit] NULL,
 CONSTRAINT [PK_ImageStore] PRIMARY KEY CLUSTERED 
(
 [ImageId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Product]    Script Date: 12-03-2017 00:16:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Product](
 [ProductId] [int] IDENTITY(1,1) NOT NULL,
 [Title] [nvarchar](200) NULL,
 [Description] [nvarchar](1000) NULL,
 [Price] [int] NULL,
 [ImageId] [int] NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED 
(
 [ProductId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
ALTER TABLE [dbo].[Product]  WITH CHECK ADD  CONSTRAINT [FK_Product_ImageStore] FOREIGN KEY([ImageId])
REFERENCES [dbo].[ImageStore] ([ImageId])
GO
ALTER TABLE [dbo].[Product] CHECK CONSTRAINT [FK_Product_ImageStore]
GO

   

All Code Factory

Part 33 - Upload and display image using JQuery in Asp.net MVC | To File server


#Expected Output 



#Controller Code(TestController.cs)


using MVCTutorial.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace MVCTutorial.Controllers
{
    public class TestController : Controller
    {

        public ActionResult Index()
        {          

            return View();
        }


        public JsonResult ImageUpload(ProductViewModel model) {

            var file = model.ImageFile;

            if (file != null) {

                var fileName = Path.GetFileName(file.FileName);
                var extention = Path.GetExtension(file.FileName);
                var filenamewithoutextension = Path.GetFileNameWithoutExtension(file.FileName);

                file.SaveAs(Server.MapPath("/UploadedImage/" + file.FileName));

                          
            }

            return Json(file.FileName, JsonRequestBehavior.AllowGet);
        
        }
    }
}


  
#Model (ProductViewModel.cs) 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCTutorial.Models
{
    public class ProductViewModel
    {
        public string ProductName { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public Nullable<int> Price { get; set; }
        public Nullable<int> ImageId { get; set; }
        public HttpPostedFileWrapper ImageFile { get; set; }
    }
}

 # View (Index.cshtml)


@model MVCTutorial.Models.ProductViewModel
@{
    ViewBag.Title = "Index";
    // Layout = null;
}

<div class="panel panel-body" style="min-height:256px">

    @*<div class="col-md-3">

        @{ Html.RenderAction("SideMenu", "Test");}

    </div>*@
    <div class="col-md-9">


        <div class="col-md-4">
            <div class="btn btn-primary">
                <input type="file" id="imageBrowes" />
            </div>
            <hr />

            <div id="imgPreview" class="thumbnail" style="display:none">
                <img class="img-responsive" id="targetImg" />
                <div class="caption">
                    <a href="#" onclick="ClearPreview()"><i class="glyphicon glyphicon-trash"></i></a>
                    <span id="description"></span>
                </div>
                <a href="#" class="btn btn-default" onclick="Uploadimage()">Upload</a>
            </div>

        </div>
       <div class="col-md-2 thumbnail" id="uploadedImage" >


       </div>
    </div>


</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>

    $(document).ready(function () {

        $("#imageBrowes").change(function () {

            var File = this.files;

            if (File && File[0]) {
                ReadImage(File[0]);
            }

        })

    })


    var ReadImage = function (file) {

        var reader = new FileReader;
        var image = new Image;

        reader.readAsDataURL(file);
        reader.onload = function (_file) {

            image.src = _file.target.result;
            image.onload = function () {

                var height = this.height;
                var width = this.width;
                var type = file.type;
                var size = ~~(file.size / 1024) + "KB";

                $("#targetImg").attr('src', _file.target.result);
                $("#description").text("Size:" + size + ", " + height + "X " + width + ", " + type + "");
                $("#imgPreview").show();

            }

        }

    }

    var ClearPreview = function () {
        $("#imageBrowes").val('');
        $("#description").text('');
        $("#imgPreview").hide();

    }

    var Uploadimage = function () {
     
        var file = $("#imageBrowes").get(0).files;
         
        var data = new FormData;
        data.append("ImageFile", file[0]);
        data.append("ProductName", "SamsungA8");

        $.ajax({

            type: "Post",
            url: "/Test/ImageUpload",
            data: data,
            contentType: false,
            processData: false,
            success: function (response) {
                ClearPreview();

                $("#uploadedImage").append('<img src="/UploadedImage/' + response + '" class="img-responsive thumbnail"/>');


            }

        })

        
        //
    }

</script>

 # Layout (_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")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/Test/Index">
                    <img alt="Brand" src="~/Content/Images/logo.png" height="20" width="20">
                </a>
            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li><a href="#"><span class="glyphicon glyphicon-home"></span></a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Services <span class="caret"></span></a>
                        <ul class="dropdown-menu" role="menu" id="myTab">
                            <li role="presentation"><a href="#music" aria-controls="music" role="tab" data-toggle="tab"><span class="glyphicon glyphicon-music"> </span> Music & Dance</a></li>
                            <li class="divider"></li>
                            <li role="presentation"><a href="#training" aria-controls="training" role="tab" data-toggle="tab"><span class="glyphicon glyphicon-book"> </span> Summar Training</a></li>
                            <li class="divider"></li>
                            <li role="presentation"><a href="#website" aria-controls="website" role="tab" data-toggle="tab"><span class="glyphicon glyphicon-cloud"> </span> Website Building</a></li>
                        </ul>

                    </li>
                    <li><a href="#">About Us</a></li>
                    <li><a href="#">Career</a></li>
                </ul>
                <form class="navbar-form navbar-left" role="search">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Search">
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>

                @if (Session["UserId"] != null) { 
                
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#">Welcome :@Session["UserName"]  </a></li>
                    <li><a href="/Test/Logout">Logout</a></li>

                </ul>
                
                }
                else { 
                 <ul class="nav navbar-nav navbar-right">
                    <li><a href="/Test/Login">Login</a></li>
                    <li><a href="/Test/Registration">Register</a></li>

                </ul>

                }
               
                }

            </div>
        </div>

    </nav>

    <div class="panel-body" style="min-height:450px">

        @RenderBody()


    </div>

    <div class="well" style="background-color:#000000;color:wheat;margin-bottom:0px">

        <div class="col-lg-4" style="margin-left:20px">

            <h3><span class="glyphicon glyphicon-map-marker"></span> Address</h3>
            <ul class="list-group list-unstyled">

                <li>Technotips Ltd.</li>
                <li>xyz Industrial Area</li>
                <li>Phase-2,New Delhi-52</li>
            </ul>
        </div>

        <div class="col-lg-4">

            <h3><span class="glyphicon glyphicon-cog"></span> Our Services</h3>
            <ul class="list-group list-unstyled">

                <li><span class="glyphicon glyphicon-music"></span> <a href="#">Musical & Dance Traning</a> </li>
                <li><span class="glyphicon glyphicon-book"></span>    <a href="#">Training in Asp.Net,Java,android etc.</a></li>
                <li><span class="glyphicon glyphicon-globe"></span> <a href="#">Web designing -corporate & Domestic</a> </li>

            </ul>
        </div>

        <div class="col-lg-3">

            <h3><span class="glyphicon glyphicon-briefcase"></span> Career</h3>
            <ul class="list-group list-unstyled">

                <li><span class="glyphicon glyphicon-music"></span> <a href="#">Musical & Dance</a> </li>
                <li><span class="glyphicon glyphicon-book"></span>  <a href="#">Summar training</a></li>
                <li><span class="glyphicon glyphicon-globe"></span>    <a href="#">Website Designing</a></li>

            </ul>
        </div>

        <div style="clear:both"></div>


    </div>


    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

    @RenderSection("scripts", required: false)


</body>
</html>


   

All Code Factory