2017-05-27 100 views
0

我有一個表單上傳文件,但無法將它與其他元素同時保存在同一模型或兩個單獨的模型中。我明白我的第一個問題是我不能嵌套表格,例如如何與其他數據同時上傳文件

@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <form class="form-horizontal"> 
     <input /> 
     <input /> 
      @using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 
      { 
       <form class="form-horizontal"> 
       <input image upload/> 
       <input /> 

      </form> 
      } 
    </form> 
} 

所以我現在有兩個獨立的形式可以很好地工作,但我想幾件事情:1。 當用戶選擇要上傳的圖片任何當前輸入的值不會被刪除2.更新與模型所有輸入的數據(所有表單元素)以及圖像到選定的模型。 3.有沒有辦法以一種形式做到這一點? (在一個單一的!)。

我將如何實現這一目標?我目前的工作情況如下。

查看:

@model client.Models.jobs 

@{ 
    ViewBag.Title = "Create Job Details"; 
} 

<br /><br /><br /> 
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <form class="form-horizontal"> 
     <fieldset> 
      <legend>Job Details</legend> 

      <!--Postcode search--><label for="inputEmail" class="col-lg-2 control-label">Job's Name</label> 
      <input name="jobname" type="text" placeholder="Job Name" /><br /><br /> 


      <label for="jobdescription" class="col-lg-2 control-label">Job Description</label> 
      <br /><br /> 
      <div class="col-lg-10"> 
       <textarea class="form-control" rows="3" name="textArea" placeholder="Write here..."></textarea> 
       <span class="help-block">The more details you enter the easier the Tradesmen can work</span> 
      </div> 

      <br /><br /><br /><br /><br /><br /> 
      <label for="uploadphotos" class="col-lg-2 control-label"> 
       Add PHOTOS (Optional) 

       @Html.LabelFor(model => model.ImageData, new { @class = "control-label col-md-2" }) 
       <input name="Image" type="file" /> 
       @Html.ValidationMessageFor(model => model.ImageData) 

       <button type="submit" value="Upload" onclick="location.href='@Url.Action("Create", "Home")'">Upload</button> 
       @ViewBag.Message 

      </label> 


      <br /><br /> 
      <label for="select" class="col-lg-2 control-label">Tell us which stage you’re at</label> 
      <div class="col-lg-10"> 
       <select class="form-control" name="stage"> 
        <option>Preplan</option> 
        <option>already started</option> 
        <option>Almost finished</option> 
        <option>Needs redone fully</option> 
       </select> 
      </div> 
      <br /><br /><br /><br /> 

      <label for="select" class="col-lg-2 control-label"> When would you like the job to start?*</label> 
      <div class="col-lg-10"> 
       <select class="form-control" name="startjob"> 
        <option>ASAP</option> 
        <option>1-2 weeks</option> 
        <option>1 month</option> 
        <option>1+</option> 
       </select> 
      </div> 
      <br /><br /><br /><br /> 
      <label for="select" class="col-lg-2 control-label">What's your approximate budget?</label> 
      <div class="col-lg-10"> 
       <select class="form-control" name="budget"> 
        <option>£0-500</option> 
        <option>£500-100</option> 
        <option>£1000-2000</option> 
        <option>£2000+</option> 
       </select> 
      </div> 


      <br /><br /><br /><br /> 





    </form> 
} 


@using (Html.BeginForm("getJobFormValues", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <form class="form-horizontal"> 
     <input name="jobname" type="text" placeholder="Job Name" /><br /><br /> 
      <button type="submit" class="btn btn-success btn-lg">Next</button> 

    </form> 

} 

@section Scripts{ 
    <script> 
     debugger 
    </script> 
} 

控制器和操作:

[AcceptVerbs(HttpVerbs.Post)] 
     public ActionResult Create(uploadedfiles pic, HttpPostedFileBase image) 
     { 
      if (ModelState.IsValid) 
      { 
       if (image != null) 
       { 
        //attach the uploaded image to the object before saving to Database 
        pic.ContentType = Convert.ToString(image.ContentLength); 
        pic.ImageData = new byte[image.ContentLength]; 
        image.InputStream.Read(pic.ImageData, 0, image.ContentLength); 

        //Save image to file 
        var filename = image.FileName; 
        var filePathOriginal = Server.MapPath("/Content/Uploads/Originals"); 
        var filePathThumbnail = Server.MapPath("/Content/Uploads/Thumbs"); 
        string savedFileName = Path.Combine(filePathOriginal, filename); 
        image.SaveAs(savedFileName); 

        //Read image back from file and create thumbnail from it 
        var imageFile = Path.Combine(Server.MapPath("~/Content/Uploads/Originals"), filename); 
        using (var srcImage = Image.FromFile(imageFile)) 
        using (var newImage = new Bitmap(100, 100)) 
        using (var graphics = Graphics.FromImage(newImage)) 
        using (var stream = new MemoryStream()) 
        { 
         graphics.SmoothingMode = SmoothingMode.AntiAlias; 
         graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; 
         graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; 
         graphics.DrawImage(srcImage, new Rectangle(0, 0, 100, 100)); 
         newImage.Save(stream, ImageFormat.Png); 
         var thumbNew = File(stream.ToArray(), "image/png"); 
         pic.ImageData = thumbNew.FileContents; 
         pic.ImageName = filename; 
        } 
       } 

       //Save model object to database 
       db.uploadedfiles.Add(pic); 

       ViewBag.Message = "Image Uploaded Successfully!!"; 

       try 
       { 
        db.SaveChanges(); 

       } 
       catch (DbEntityValidationException e) 
       { 
        foreach (var eve in e.EntityValidationErrors) 
        { 
         Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", 
          eve.Entry.Entity.GetType().Name, eve.Entry.State); 
         foreach (var ve in eve.ValidationErrors) 
         { 
          Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", 
           ve.PropertyName, ve.ErrorMessage); 
         } 
        } 
        throw; 
       } 

       ViewBag.Message = "Image Uploaded Successfully!!"; 

       return View("JobDetails"); 
       //return RedirectToAction("getJobFormValues"); 

      } 

      return View("JobDetails"); 
     } 

[HttpPost] 
     public ActionResult getJobFormValues(jobs job) 
     { 
      string quoteSearch = Request["quoteSearch"]; 
      string jobname = Request["jobname"]; 
      string jobmessage = Request["textArea"]; 
      string uploadedphoto = Request["uploadphotos"]; 
      string stage = Request["stage"]; 
      string startjob = Request["startjob"]; 
      string budget = Request["budget"]; 
      int imgid = 2; 



      //Save model object to database 
      //Save personal details model object to database 
      if (ModelState.IsValid) 
      { 

       //Save model object to database 
       db.jobs.Add(new jobs 
       { 
        name = jobname, 
        jobmessage = jobmessage, 
        //iscomplete 
        //jobbyuserid 
        //responsibletradesmanid 
        //jobmessage 
        stage = stage, 
        startjob = startjob, 
        budget = Convert.ToInt32(budget), 
        ImageId = imgid 
        //ImageName 
        //ImageAlt 
        //ImageData 
        //ContentType 
       }); 

       try 
       { 
        db.SaveChanges(); 
       } 
       catch (DbEntityValidationException e) 
       { 
        foreach (var eve in e.EntityValidationErrors) 
        { 
         Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", 
          eve.Entry.Entity.GetType().Name, eve.Entry.State); 
         foreach (var ve in eve.ValidationErrors) 
         { 
          Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", 
           ve.PropertyName, ve.ErrorMessage); 
         } 
        } 
        throw; 
       } 




      return RedirectToAction("PersonalDetails", new 
       { 
        quoteSearch = quoteSearch, 
        jobname = jobname, 
        jobmessage = jobmessage, 
        uploadedphoto = uploadedphoto, 
        stage = stage, 
        startjob = startjob, 
        budget = budget 
       }); 
      }//model state 

      return View("JobDetails"); 

     } 

回答

0
I hope this will help anyone in same situation(i.e. learners!). After hunting around I realised that if (I could be wrong!) working with complex objects such as images text will just be strung along anyway with the .Add and .Save as long as they're part of the Model like so: 
namespace client.Models 
{ 
    using System; 
    using System.Collections.Generic; 

    public partial class jobs 
    { 
     public int id { get; set; } 
     public string name { get; set; } 
     public Nullable<bool> iscomplete { get; set; } 
     public Nullable<int> jobbyuserid { get; set; } 
     public Nullable<int> responsibletradesmanid { get; set; } 
     public string jobmessage { get; set; } 
     public string stage { get; set; } 
     public string startjob { get; set; } 
     public int ImageId { get; set; } 
     public string ImageName { get; set; } 
     public string ImageAlt { get; set; } 
     public byte[] ImageData { get; set; } 
     public string ContentType { get; set; } 
     public string Budget { get; set; } 
    } 
    } 

Then chop up the Action to create,hold,save,image data etc but MOST IMPORTANTLY you do not need to define any fields from the form 
    `(string quoteSearch = Request["quoteSearch"]; etc.)` as they will be updated with the model. So the only difference here is that I have removed the form requests and removed saving single items like 

     //Save model object to database 
        db.jobs.Add(new jobs 
        { 
         name = jobname, 

and then only used one action for both image and form data all put together nicely like so: 




    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Create(jobs pic, HttpPostedFileBase image) 
    { 
    var context = System.Web.HttpContext.Current; 
    var contextBase = new HttpContextWrapper(context); 
    ////Pull out the current username from cookie into var 
    //usernameCookie = new HttpCookie("CurrentUsername"); 
    //usernameCookie = contextBase.User.Request.Cookies["CurrentUsername"]; 

     //Get email from OWIN 
     string usernameCookie = contextBase.User.Identity.Name.ToString(); 

     if (ModelState.IsValid) 
     { 
      if (image != null) 
      { 
       //attach the uploaded image to the object before saving to 


     Database 
        pic.ContentType = Convert.ToString(image.ContentLength); 
        pic.ImageData = new byte[image.ContentLength]; 
        image.InputStream.Read(pic.ImageData, 0, 
     image.ContentLength); 

        //Save image to file 
        var filename = image.FileName; 
        var filePathOriginal = 
     Server.MapPath("/Content/Uploads/Originals"); 
        var filePathThumbnail = 
     Server.MapPath("/Content/Uploads/Thumbs"); 
        string savedFileName = Path.Combine(filePathOriginal, 
     filename); 
        image.SaveAs(savedFileName); 

        //Read image back from file and create thumbnail from it 
        var imageFile = 
     Path.Combine(Server.MapPath("~/Content/Uploads/Originals"), filename); 
        using (var srcImage = Image.FromFile(imageFile)) 
        using (var newImage = new Bitmap(100, 100)) 
        using (var graphics = Graphics.FromImage(newImage)) 
        using (var stream = new MemoryStream()) 
        { 
         graphics.SmoothingMode = SmoothingMode.AntiAlias; 
         graphics.InterpolationMode = 
     InterpolationMode.HighQualityBicubic; 
         graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; 
         graphics.DrawImage(srcImage, new Rectangle(0, 0, 100, 
     100)); 
         newImage.Save(stream, ImageFormat.Png); 
         var thumbNew = File(stream.ToArray(), "image/png"); 
         pic.ImageData = thumbNew.FileContents; 
         pic.ImageName = filename; 
        } 
       } 

       //Save model object to database 
       db.jobs.Add(pic); 

       ViewBag.Message = "Image Uploaded Successfully!!"; 

       int newJobID = 0; 

       try 
      { 
       //this saves model with image 
       db.SaveChanges(); 

       //get last inserted row ID 
       newJobID = pic.id; 

       //get row based on last inserted for updating the imageID as we want them correlate 
       // make sure you have the right column/variable used here 
       var rowToUpdate = db.jobs.FirstOrDefault(x => x.id == newJobID); 
       if (rowToUpdate == null) throw new Exception("Invalid id: " + newJobID); 
       // this variable is tracked by the db context 
       rowToUpdate.ImageId = newJobID; 

       var addLoggedInUserToTable = db.tradesusers.FirstOrDefault(e => e.email == usernameCookie); 
       if (addLoggedInUserToTable == null) throw new Exception("Invalid id: " + usernameCookie); 
       addLoggedInUserToTable.lastpostedjobid = newJobID; 

       if (addLoggedInUserToTable.email == usernameCookie) { 
       rowToUpdate.jobbyuserid = addLoggedInUserToTable.id; 
      } 

       //reasave Model with updated ID 
       db.SaveChanges(); 

      } 
      catch (DbEntityValidationException e) 
      { 
       foreach (var eve in e.EntityValidationErrors) 
       { 
        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", 
         eve.Entry.Entity.GetType().Name, eve.Entry.State); 
        foreach (var ve in eve.ValidationErrors) 
        { 
         Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", 
          ve.PropertyName, ve.ErrorMessage); 
        } 
       } 
       throw; 
      } 

      ViewBag.Message = "Image Uploaded Successfully!!"; 

      //return View("JobDetails"); 
      return RedirectToAction("PersonalDetails", new { usernameCookie = usernameCookie }); 

     } 

     return View("JobDetails"); 
    }`enter code here` 

I believe retrieving the images is a bit more straight forward! ;-) 
相關問題