如何使用实体框架C#mvc上传图像?

时间:2016-10-21 08:04:13

标签: c# entity-framework

我使用ASP.NET c#mvc和实体框架来构建一个网站。所以我想为注册用户创建可编辑的用户配置文件。在其中,我编写了一个图像上传部分,并没有成功地为我解决。

这是我的View文件(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>

它将提供如下的UI。

enter image description here

我的模型文件如下所示。

    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; }
    } 
}

我的控制器看起来像这样(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);

        }
    }
}

我的数据库的设计是;

enter image description here

我的DbContext文件如下所示;

    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; }
    }
}

但是当我执行所有这些事情时,我的〜/ Content / Images文件没有我上传的图像文件。并且它会给我视图中的错误如下。

enter image description here

实际上我想将数据库和图像中相关图像文件的路径保存在以下层次结构的〜/ Content / Images文件夹中。

enter image description here

我对这个环境特别是Entity Framework非常陌生。因此,我不知道如何纠正我的代码以获得我期望的内容。

1 个答案:

答案 0 :(得分:0)

首先,您要做的是将该图像复制并过去到您的图像文件夹

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

然后将该路径保存到您的数据库中。