2016-10-21 5 views
0

Webサイトを構築するために、エンティティフレームワークでASP.NET c#mvcを使用しています。だから私は編集可能な登録ユーザーのユーザープロファイルを作成したいと思います。その中で私は画像のアップロード部分をコーディングしていて、それは私のためにうまくいきませんでした。エンティティフレームワークC#mvcを使用して画像をアップロードするには?

これは私のビューファイル(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; } 
    } 
} 

しかし、私がこれらのすべてを実行しているとき、My〜/ Content/Imagesファイルには、アップロードした画像ファイルがありません。そしてそれは私に次のようにビューにエラーを与えるでしょう。

enter image description here

は実際に私がどの階層を以下に〜/コンテンツ/ Imagesフォルダ内の関連画像データベース内のファイルや画像へのパスを保存したかったです。

enter image description here

私はこの環境に特別Entity Frameworkのに非常に新しいです。だから私は私のコードを修正して私が期待しているものを得る方法を知らない。あなたがしなければならない

+2

私はこれが "less is more"の場所だと思っています。あなたはバレル負荷のコードを与えていますが、エラーが発生している行については忘れています。あなたの質問を書き直し、[最​​小、完全で検証可能な例]を与えてください(http://stackoverflow.com/help/mcve)。 –

答えて

0

まず、あなたのデータベースにそのパスを保存し、あなたの画像フォルダ

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

にコピーして、その画像を過ぎています。

関連する問題