简体   繁体   中英

How to upload an image using entity framework C# mvc?

I'm using ASP.NET c# mvc with entity framework to build a web site. So I want to create user profile for the registered user which is editable. Within that i have coded for a image upload part and it was not successfully worked out for me.

This is my View file (Manage.cshtml)

    @model TheFoody.Models.ManageViewModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script>
    function editFunc() {
        document.getElementById("Photo").disabled = false;
        document.getElementById("FirstName").disabled = false;
        document.getElementById("LastName").disabled = false;
        document.getElementById("Email").disabled = false;
        document.getElementById("UserType").disabled = false;
        document.getElementById("Address").disabled = false;
        document.getElementById("City").disabled = false;
        document.getElementById("District").disabled = false;
        document.getElementById("Phone").disabled = false;
        //document.getElementById("Photo").disabled = false;
        document.getElementById("PostCode").disabled = false;
        document.getElementById("Status").disabled = false;
    }
    function reload() {
        window.location.href = "http://localhost:1672/Manage";
    }


</script>




<div class="breadcrumb-wrapper">
    <div class="container">
        <ol class="breadcrumb-list booking-step">
            <li><a href="#">Home</a></li>
            <li><span>User Profile</span></li>
        </ol>
    </div>
</div>

<div class="admin-container-wrapper">
    <div class="container">
        <div class="GridLex-gap-15-wrappper">
            <div class="GridLex-grid-noGutter-equalHeight">
                <div class="GridLex-col-3_sm-4_xs-12">
                    <div class="admin-sidebar">
                        <div class="admin-user-item">
                            <div class="image">
                                <img src="http://localhost:33409/images/man/01.jpg" alt="image" class="img-circle" />
                            </div>
                            <h4>John Doe</h4>
                            <p class="user-role">Foodies</p>
                        </div>
                        <div class="admin-user-action text-center">
                            <a href="#" class="btn btn-primary btn-sm" onclick="editFunc()">Edit</a>
                            <a href="#" class="btn btn-primary btn-sm btn-inverse">Deactivate</a>
                        </div>
                        <ul class="admin-user-menu clearfix">
                            <li>
                                <a href="#"><i class="fa fa-tachometer"></i> Dashboard</a>
                            </li>
                            <li class="active">
                                <a href="#" onclick="reload()"><i class="fa fa-user"></i> Profile</a>
                            </li>
                            <li>
                                <a href="http://localhost:1672/ChangePassword/ChangePassword"><i class="fa fa-key"></i> Change Password</a>
                            </li>
                            <li>
                                <a href="#"><i class="fa fa-bookmark"></i> Favourite Restaurant</a>
                            </li>
                            <li>
                                <a href="#"><i class="fa fa-sign-out"></i> Logout</a>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="GridLex-col-9_sm-8_xs-12">
                    <div class="admin-content-wrapper">
                        <div class="admin-section-title">
                            <h2>Profile</h2>
                            <p>Enquire explain another he in brandon enjoyed be service.</p>
                        </div>
                        <!--<form class="post-form-wrapper" action="http://localhost:33409/UpdateProfile/Edit" id="updateForm" method="POST">-->
                        @using (Html.BeginForm("Manage", "Manage", new { @id = "updateForm", @class = "post-form-wrapper" }, FormMethod.Post))
                        {
                            @Html.AntiForgeryToken();
                            <div class="row gap-20">
                                <div class="col-sm-6 col-md-4">
                                    @ViewBag.Error
                                    <div class="form-group bootstrap-fileinput-style-01">
                                        <label>Photo</label>
                                        <input type="file" name="Photo" id="Photo" disabled>

                                        @*@Html.HiddenFor(model => model.Photo, new { @class = "form-control", disabled = "disabled" })*@
                                        @*<input type="hidden" value="default" id="photo" name="photo" />*@
                                        <span class="font12 font-italic">** photo must not bigger than 250kb</span>
                                    </div>

                                </div>
                                <div class="clear"></div>
                                <div class="col-sm-6 col-md-4">
                                    <div class="form-group">
                                        <label>First Name</label>
                                        @Html.TextBoxFor(model => model.FirstName, new { @class = "form-control", disabled = "disabled" })
                                        @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="col-sm-6 col-md-4">
                                    <div class="form-group">
                                        <label>Last Name</label>
                                        @Html.TextBoxFor(model => model.LastName, new { @class = "form-control", disabled = "disabled" })
                                        @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
                                    </div>
                                </div>

                                <div class="col-sm-6 col-md-4">
                                    <div class="form-group">
                                        <label>Email</label>
                                        @*<input type="email" class="form-control" value=Session["UserEmail"].tostring() id="email" name="email" disabled>*@
                                        @Html.TextBoxFor(model => model.Email, new { @class = "form-control", disabled = "disabled"})
                                        @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                                    </div>
                                </div>

                                <div class="clear"></div>
                                <div class="col-sm-6 col-md-4">
                                    <div class="form-group">
                                        <label>Address</label>
                                        @*<input type="text" class="form-control" value="254" id="address" name="address" disabled>*@
                                        @Html.TextBoxFor(model => model.Address, new { @class = "form-control", disabled = "disabled" })
                                        @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
                                    </div>
                                </div>

                                <div class="clear"></div>
                                <div class="col-sm-6 col-md-4">
                                    <div class="form-group">
                                        <label>District</label>
                                        @*<input type="text" class="form-control" value="254" id="district" name="district" disabled>*@
                                        @Html.TextBoxFor(model => model.District, new { @class = "form-control", disabled = "disabled" })
                                        @Html.ValidationMessageFor(model => model.District, "", new { @class = "text-danger" })
                                    </div>
                                </div>

                                <div class="col-sm-6 col-md-4">
                                    <div class="form-group">
                                        <label>City/town</label>
                                        @*<input type="text" class="form-control" value="Somewhere " id="city" name="city" disabled>*@
                                        @Html.TextBoxFor(model => model.City, new { @class = "form-control", disabled = "disabled" })
                                        @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
                                    </div>
                                </div>

                                <div class="col-sm-6 col-md-4">
                                    <div class="form-group">
                                        <label>PostCode</label>
                                        @*<input type="text" class="form-control" value="Somewhere " id="postcode" name="postcode" disabled>*@
                                        @Html.TextBoxFor(model => model.PostCode, new { @class = "form-control", disabled = "disabled" })
                                        @Html.ValidationMessageFor(model => model.PostCode, "", new { @class = "text-danger" })
                                    </div>
                                </div>

                                <div class="col-sm-6 col-md-4">
                                    <div class="form-group">
                                        <label>UserType</label>
                                    </div>

                                    <div class="col-sm-6 col-md-4">

                                        @{
                                                    List<SelectListItem> listItemsUserType = new List<SelectListItem>();
                                                    listItemsUserType.Add(new SelectListItem
                                                         {
                                                             Text = "Admin",
                                                             Value = "Admin"
                                                         });
                                                    listItemsUserType.Add(new SelectListItem
                                                         {
                                                             Text = "Customer",
                                                             Value = "Customer",
                                                             Selected = true
                                                         });
                                                    listItemsUserType.Add(new SelectListItem
                                                         {
                                                             Text = "Business",
                                                             Value = "Business"
                                                         });
                                        }

                                        @Html.DropDownListFor(model => model.UserType, listItemsUserType, "-- Select Status --", new { @class = "form-control",disabled = "disabled" })


                                    </div>
                                </div>

                                <div class="col-sm-6 col-md-4">
                                    <div class="form-group">
                                        <label>Status</label>
                                    </div>

                                    <div class="col-sm-6 col-md-4">

                                        @{
                                                    List<SelectListItem> listItemsStatus = new List<SelectListItem>();
                                                    listItemsStatus.Add(new SelectListItem
                                                         {
                                                             Text = "Availble",
                                                             Value = "Available",
                                                             Selected = true
                                                         });
                                                    listItemsStatus.Add(new SelectListItem
                                                         {
                                                             Text = "Not Available",
                                                             Value = "Not Available"
                                                         });
                                        }

                                        @Html.DropDownListFor(model => model.Status, listItemsStatus, "-- Select Status --", new { @class = "form-control",disabled = "disabled" })


                                    </div>
                                </div>


                                <div class="clear"></div>
                                <div class="col-sm-6 col-md-4">
                                    <div class="form-group">
                                        <label>Phone Number</label>
                                        @*<input type="text" class="form-control" value="+66-85-221-5489" id="phone" name="phone" disabled>*@
                                        @Html.TextBoxFor(model => model.Phone, new { @class = "form-control", disabled = "disabled" })
                                        @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
                                    </div>
                                </div>

                                <div class="clear"></div>
                                <div class="col-sm-12 mt-10">
                                    @*<input type="submit" onclick="document.getElementById('updateform').submit()" class="btn btn-primary" value="Save" />*@

                                    <input type="submit" class="btn btn-primary" value="Save" />

                                    <a href="#" class="btn btn-primary btn-inverse">Cancel</a>
                                </div>
                            </div>
                        }
                        <!--</form>-->
                    </div>
                </div>

            </div>
        </div>
    </div>

</div>

And it will give a UI like below.

在此处输入图片说明

And my Model file is like below.

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

namespace TheFoody.Models
{
    public class ManageViewModel
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string Email { get; set; }

        public string Phone { get; set; }

        public string Photo { get; set; }

        public string Address { get; set; }

        public string City { get; set; }

        public int PostCode { get; set; }

        public string District { get; set; }

        public string UserType { get; set; }

        public string Status { get; set; }
    } 
}

And my Controller looks like this (ManageController.cs)

    using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TheFoody.DataAccess;
using TheFoody.Models;

namespace TheFoody.Controllers
{
    public class ManageController : Controller
    {
        //ManageContext db = new ManageContext();
        //
         //GET: /Manage/
        public ActionResult Manage()
        {
            //LoadData();
            var manageviewmodel = new ManageViewModel() { Email = Session["UserEmail"].ToString() };
            return View(manageviewmodel);
        }

        private bool isValidContentType(string contentType)
        {
            return contentType.Equals("Images/png") || contentType.Equals("Images/gif") || contentType.Equals("Images/jpg") || contentType.Equals("Images/jpeg");
        }

        private bool isValidContentLength(int contentLength)
        {
            return (contentLength / 1024) / 1024 < 1; //1MB
        }

        [HttpPost]
        public ActionResult Manage(ManageViewModel manageviewmodel, HttpPostedFileBase Photo)
        {
            TheFoodyContext db = new TheFoodyContext();
            User user_to_update = db.Users.SingleOrDefault(s => s.email == manageviewmodel.Email);

            if (ModelState.IsValid)
            {

                try
                {

                    if (!isValidContentType(Photo.ContentType))
                    {
                        ViewBag.Error = "Only JPG , JPEG , GIF & PNG are allowed!";
                        return View("Manage");
                    }

                    else if (!isValidContentLength(Photo.ContentLength))
                    {
                        ViewBag.Error = "Your File is too Large!";
                        return View("Manage");
                    }

                    else
                    {

                        if (user_to_update != null && (Photo != null && Photo.ContentLength > 0))
                        {

                            var fileName = Path.GetFileName(Photo.FileName);
                            var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
                            Photo.SaveAs(path);

                            user_to_update.email = manageviewmodel.Email;
                            user_to_update.fname = manageviewmodel.FirstName;
                            user_to_update.lname = manageviewmodel.LastName;
                            user_to_update.phone = manageviewmodel.Phone;
                            //user_to_update.photo = manageviewmodel.Photo;
                            user_to_update.address = manageviewmodel.Address;
                            user_to_update.city = manageviewmodel.City;
                            user_to_update.postcode = manageviewmodel.PostCode;
                            user_to_update.district = manageviewmodel.District;
                            user_to_update.user_type = manageviewmodel.UserType;
                            user_to_update.status = manageviewmodel.Status;

                            db.SaveChanges();

                            return RedirectToAction("Manage");
                        }
                    }


                }
                catch (Exception ex)
                {
                    return View("Error");
                }
                return View(manageviewmodel);
            }

            return View(manageviewmodel);

        }
    }
}

And the design of My database is;

在此处输入图片说明

And my DbContext file looks as below;

    namespace TheFoody.DataAccess
{
    using System;
    using System.Collections.Generic;

    public partial class User
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public User()
        {
            this.Restaurants = new HashSet<Restaurant>();
        }

        public string email { get; set; }
        public string password { get; set; }
        public string fname { get; set; }
        public string lname { get; set; }
        public string phone { get; set; }
        public string photo { get; set; }
        public string address { get; set; }
        public string city { get; set; }
        public Nullable<decimal> postcode { get; set; }
        public string district { get; set; }
        public string user_type { get; set; }
        public string status { get; set; }
        public System.DateTime created_date { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Restaurant> Restaurants { get; set; }
    }
}

But when i'm executing all these things My ~/Content/Images file does not have the image file that i have uploaded. And it will give me the error to the view as follows.

在此处输入图片说明

Actually I wanted to save the path to the relevant image file in the database and image in the ~/Content/Images folder which in following hierarchy.

在此处输入图片说明

I'm very new to this environment specially Entity Framework. So i don't know how to correct my code to get what i'm expected.

First you have to do is copy and past that image to your image folder

System.IO.File.Copy("source", "destination");

Then save that path to your data base.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM