How to retrieve image from database without using Entity Framework in ASP.NET MVC4

user3493106

I'm new to ASP.NET MVC and I need some help from you. I'm trying to create insert and get image from database and I can save an image into binary format but I can't get it back into image format

My output is like below image

enter image description here

Here is my view

@model IEnumerable<HelphoProject.Models.Property>
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<p>
    hi you are now in Index page of HElpho
</p>

<div>
     @Html.DropDownList("CityID", (IEnumerable<SelectListItem>)ViewBag.CityList,"Select City")
</div>

<div>
    @Html.DropDownList("propertyTypeID",(IEnumerable<SelectListItem>)ViewBag.PropertyTypeList,"Select PropertyType")
</div>

@Html.ActionLink("Add New Property", "AddNewProperty",null, new { @class="btn btn-primary"})

<table class="table" style="width: 1200px;">
    <tr>
        <th>

            <b>ImageID</b>
        </th>
        <th>
            <b>CityID</b>
        </th>
        <th>
            <b>TypeID</b>
        </th>
        <th>
            <b>Image</b>
        </th>
        <th>
            <b>Description</b>
        </th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(a =>item.ImageID )
            </td>
            <td>
                @Html.DisplayFor(a=>item.CityID)
            </td>
            <td>
                @Html.DisplayFor(a=>item.propertyTypeID)
            </td>
           <td style="width: 500px;">
                @Html.Raw(item.Image)
            </td>
            <td>
             <img src="/Content/RetrieveImage/@item.ImageID" alt="" height=100 width=200 />
            </td>
            <td>
                @Html.DisplayFor(a=>item.Description)
            </td>
            <td style="width: 500px;">

                @*@Html.Raw(item.content)*@
            </td>
            <td>

            </td>
            <td>
            @*    @Html.DisplayFor(modelItem => item.Description)*@
            </td>
        </tr>
    }
</table>

Here is my controller code:

using HelphoProject.DataAccessLayer;
using HelphoProject.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HelphoProject.Controllers
{
    public class PropertyController : Controller
    {
        //
        // GET: /Property/
        [HttpGet]
        public ActionResult Index()
        {
            Cities();
            getPropertyType();

            readwriteProperty writedata = new readwriteProperty();
            List<Property> propertyList = writedata.getproperties();
            var content = propertyList.Select(item => new Property()
            {
                ImageID = item.ImageID,
                CityID = item.CityID,
                propertyTypeID = item.propertyTypeID,
                Image = item.Image,
                Description = item.Description
            });

            List<Property> contentModel = content.Select(item => new Property()
                {

                    ImageID = item.ImageID,
                    CityID = item.CityID,
                    propertyTypeID = item.propertyTypeID,
                    Image = item.Image,
                    Description = item.Description 
                }).ToList();
            RetrieveImage(1);

            return View(contentModel);
        }

        public ActionResult RetrieveImage(int id)
        {
            byte[] cover = GetImageFromDataBase(id);
            if (cover != null)
            {
                return File(cover, "image/jpg");
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public byte[] GetImageFromDataBase(int Id)
        {
            readwriteProperty writedata = new readwriteProperty();

            byte[] Image = writedata.getImageFromDB();
            return Image;
        }

        public ActionResult Cities()
        {
            readwriteCity dbconnection = new readwriteCity();
            List<City> pcontent = new List<City>();
            {
                //Get all page content from TblHome table
                pcontent = dbconnection.getAllCities();

            };
            List<SelectListItem> cityList = new List<SelectListItem>();
            //List<string> items = new List<string>(); 
            foreach (var item in pcontent)
            {
                cityList.Add(new SelectListItem
                {
                    Text = item.CityName,
                    Value = item.CityID.ToString()
                });
            }

            ViewBag.CityList = cityList;
            return View();
        }

        public ActionResult getPropertyType()
        {
            readwritePropertyType dbconnection = new readwritePropertyType();
            List<PropertyType> pcontent = new List<PropertyType>();
            {
               // Get all page content from TblHome table
                pcontent = dbconnection.getAllPropertyType();

            };
            List<SelectListItem> propertyTypeList = new List<SelectListItem>();
            List<string> items = new List<string>(); 
            foreach (var item in pcontent)
            {
                propertyTypeList.Add(new SelectListItem
                {
                    Text = item.propertyType,
                    Value = item.propertyTypeID.ToString()
                });
            }

            ViewBag.PropertyTypeList = propertyTypeList;

            return View();
        }

        public ActionResult AddNewProperty()
        {
            Cities();
            getPropertyType();
            return View();
        }

        [HttpPost]
        public ActionResult AddNewProperty(Property objProperty)
        {

            HttpPostedFileBase file = Request.Files["ImageData"];
            readwriteProperty writedata = new readwriteProperty();
            string str = writedata.SaveProperty(file, objProperty);
            if (str == "Data Saved Successfully")
            {
                return RedirectToAction("Index");
            }
            return View(objProperty);
        }
    } 
}

Here is my model:

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


namespace HelphoProject.Models
{
    public class Property
    {
        public int ImageID { get; set; }
        public int CityID { get; set; }
        public int propertyTypeID { get; set; }

        [Required]
        public byte[] Image { get; set; }

        public string Description { get; set; }
    }
}

And I have used one more thing to connect with database

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using HelphoProject.Models;
using System.IO;

namespace HelphoProject.DataAccessLayer
{
    public class readwriteProperty
    {

        SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ConnectionString);
        SqlCommand cmd;
        SqlDataAdapter sda;
        DataTable dt;

        public string SaveProperty(HttpPostedFileBase file, Property objproperty)
        {
            objproperty.Image = ConvertToBytes(file,null);

            cmd = new SqlCommand("spSaveProperty", cn);
            cmd.CommandType = CommandType.StoredProcedure;

            // cmd.Parameters.AddWithValue("@intStateID", objCity.StateID);
            cmd.Parameters.AddWithValue("@ImageID", objproperty.ImageID);
            cmd.Parameters.AddWithValue("@CityID", objproperty.CityID);
            cmd.Parameters.AddWithValue("@TypeID", objproperty.propertyTypeID);
            cmd.Parameters.AddWithValue("@Image", objproperty.Image);
            cmd.Parameters.AddWithValue("@Description", objproperty.Description);
            cn.Open();
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                return "Datat Not Saved Successfully";
            }
            cn.Close();

            return "Data Saved Successfully";
        }

        public byte[] getImageFromDB()
        {
            cn.Open();
            sda = new SqlDataAdapter("select Image FROM  tblImages", cn);
            dt = new DataTable();
            sda.Fill(dt);

            Property objmainProperty = new Property();
            foreach (DataRow dr in dt.Rows)
            {
                Property objProperty = new Property();
                objProperty.Image=(byte[])dr["Image"];
                objmainProperty.Image = objProperty.Image;
            }
            cn.Close();
            return objmainProperty.Image;
          }

        public List<Property> getproperties()
        {
            cn.Open();
            sda = new SqlDataAdapter("select ImageID,CityID,TypeID,Image,Description from tblImages", cn);
            dt = new DataTable();
            sda.Fill(dt);

            List<Property> properties = new List<Property>();

            foreach(DataRow dr in dt.Rows)
            {
                Property objProperty = new Property();
                objProperty.ImageID = Convert.ToInt16(dr["ImageID"]);
                objProperty.CityID = Convert.ToInt16(dr["CityID"]);
                objProperty.propertyTypeID = Convert.ToInt16(dr["TypeID"]);
                objProperty.Image = (byte[])dr["Image"];
                objProperty.Description = dr["Description"].ToString();

                properties.Add(objProperty);
            }

            cn.Close();
            return properties;
        }

        public byte[] ConvertToBytes(HttpPostedFileBase image,Property objproperty)
        {
            if (image != null)
            {
                byte[] imageBytes = null;
                BinaryReader reader = new BinaryReader(image.InputStream);
                imageBytes = reader.ReadBytes((int)image.ContentLength);
                return imageBytes;
            }
            else
            {
                byte[] imageBytes = objproperty.Image;
                BinaryReader reader = new BinaryReader(image.InputStream);
                imageBytes = reader.ReadBytes((int)image.ContentLength);
                return imageBytes;
            }
        }
    }
}

Using this code I can upload and save my images in to database and I can get all data from data. I can get image also but in binary format I think you can understand more after watching below image

user3922585

You have used the wrong model name. Change

img src="/Content/RetrieveImage/@item.ImageID" alt="" height=100 width=200 

to

img src="/Property/RetrieveImage/@item.ImageID" alt="" height=100 width=200 

in view section.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to retrieve image from database without using Entity Framework in ASP.NET MVC4

From Dev

how to load binary image from database to imagebox.imageurl in asp.net(NO MVC) using entity framework

From Dev

how to load binary image from database to imagebox.imageurl in asp.net(NO MVC) using entity framework

From Dev

How to display table from SQL Server using ASP NET MVC5 without using Entity Framework?

From Dev

How to retrieve value from a form and insert into Modal Box using asp.net mvc4

From Dev

ASP.NET MVC without Entity Framework database connection

From Dev

How to use a Oracle database in ASP.NET without Entity Framework?

From Dev

How to retrieve binary image from database using C# in ASP.NET

From Dev

How to retrieve binary image from database using C# in ASP.NET

From Dev

How to perform edit function in MVC4 without using entity framework?

From Dev

I have mixed Create view and index view codes in one view. So, How to retrieve data from a database by that view in asp.net MVC4?

From Dev

How to Read Record From Database in ASP.MVC Core using Entity Framework Core 1.0

From Dev

Pass dropdownlist value from View to Controller in Asp.Net MVC4 without using jquery or javascript?

From Dev

Saving images to database with asp.net mvc 4 + Entity Framework

From Dev

Retrieve image from database in mvc.net

From Dev

Using ASP.NET MVC with entity framework

From Dev

How to set the background image in asp.net mvc4

From Dev

.NET Membership in ASP.NET MVC4 and Entity Framework with Oracle as Db

From Dev

PieChart in mvc4 from Entity Framework

From Dev

bind menu and submenu from database in asp net core entity framework mvc

From Dev

Entity Framework profiler - ASP.NET MVC4 with EF 6 -Unable to determine the provider name

From Dev

Entity Framework profiler - ASP.NET MVC4 with EF 6 -Unable to determine the provider name

From Dev

ASP.NET MVC4 Entity Framework db.SaveChanges() Condition not working

From Dev

How to retrieve one column value from one table using asp .net mvc 4

From Dev

Add Database View in Entity Framework on ASP.NET MVC

From Dev

Struggling with saving data to database in ASP.NET MVC with Entity Framework

From Dev

ASP.NET MVC without Models and Entity Framework

From Dev

How to use ASP.NET Identity 3.0 without Entity Framework

From Dev

How to use Identity with Entity Framework database first in ASP.NET MVC

Related Related

  1. 1

    How to retrieve image from database without using Entity Framework in ASP.NET MVC4

  2. 2

    how to load binary image from database to imagebox.imageurl in asp.net(NO MVC) using entity framework

  3. 3

    how to load binary image from database to imagebox.imageurl in asp.net(NO MVC) using entity framework

  4. 4

    How to display table from SQL Server using ASP NET MVC5 without using Entity Framework?

  5. 5

    How to retrieve value from a form and insert into Modal Box using asp.net mvc4

  6. 6

    ASP.NET MVC without Entity Framework database connection

  7. 7

    How to use a Oracle database in ASP.NET without Entity Framework?

  8. 8

    How to retrieve binary image from database using C# in ASP.NET

  9. 9

    How to retrieve binary image from database using C# in ASP.NET

  10. 10

    How to perform edit function in MVC4 without using entity framework?

  11. 11

    I have mixed Create view and index view codes in one view. So, How to retrieve data from a database by that view in asp.net MVC4?

  12. 12

    How to Read Record From Database in ASP.MVC Core using Entity Framework Core 1.0

  13. 13

    Pass dropdownlist value from View to Controller in Asp.Net MVC4 without using jquery or javascript?

  14. 14

    Saving images to database with asp.net mvc 4 + Entity Framework

  15. 15

    Retrieve image from database in mvc.net

  16. 16

    Using ASP.NET MVC with entity framework

  17. 17

    How to set the background image in asp.net mvc4

  18. 18

    .NET Membership in ASP.NET MVC4 and Entity Framework with Oracle as Db

  19. 19

    PieChart in mvc4 from Entity Framework

  20. 20

    bind menu and submenu from database in asp net core entity framework mvc

  21. 21

    Entity Framework profiler - ASP.NET MVC4 with EF 6 -Unable to determine the provider name

  22. 22

    Entity Framework profiler - ASP.NET MVC4 with EF 6 -Unable to determine the provider name

  23. 23

    ASP.NET MVC4 Entity Framework db.SaveChanges() Condition not working

  24. 24

    How to retrieve one column value from one table using asp .net mvc 4

  25. 25

    Add Database View in Entity Framework on ASP.NET MVC

  26. 26

    Struggling with saving data to database in ASP.NET MVC with Entity Framework

  27. 27

    ASP.NET MVC without Models and Entity Framework

  28. 28

    How to use ASP.NET Identity 3.0 without Entity Framework

  29. 29

    How to use Identity with Entity Framework database first in ASP.NET MVC

HotTag

Archive