MVC3, multiple file uploads, model binding

It is possible to update a complex model (transaction). The complex model has properties that can have multiple attachments (files), so that the user can upload multiple files at once in this form, and I'm trying to save these files in a database.

I successfully posted several files on the server, the next blog entry is http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx .

However, in order to save these files so that I can track which files belong to the object of the complex model (Transaction), and therefore show them later in the appropriate places, I need to somehow link the file uploaded to the object to which it belongs, but since all files fall under file names, I don't know how I can do this.

Here is a simplified complex model:

public class Transaction { [Key] public int Id { get; set; } public virtual PurchaseRequisition PurchaseRequisition { get; set; } public virtual Evaluation Evaluation { get; set; } } 

Properties of a complex model:

 public class PurchaseRequisition { [Key, ForeignKey("Transaction")] public int TransactionId { get; set; } public virtual Transaction Transaction { get; set; } [Display(Name = "Specifications/Requisitioner Notes")] public virtual ICollection<Attachment> SpecsRequisitionerNotesFiles { get; set; } } public class Evaluation { [Key, ForeignKey("Transaction")] public int TransactionId { get; set; } public virtual Transaction Transaction { get; set; } public virtual ICollection<Attachment> BidResultsFiles { get; set; } } public abstract class Attachment { [Key] public int Id { get; set; } public string FileName { get; set; } public string FileExtension { get; set; } public byte[] Data { get; set; } public Boolean Deleted { get; set; } } 

Here is the controller:

 [HttpPost] public ActionResult Create(TransactionViewModel model, IEnumerable<HttpPostedFileBase> files) { //save to database } 
+6
source share
1 answer

Create separate sections in the view for purchase requisitions and bid results. Something like that:

 <form action="" method="post" enctype="multipart/form-data"> <h3>Purchase Requistions</h3> <label for="file1">Filename:</label> <input type="file" name="purchasereqs" id="file1" /> <label for="file2">Filename:</label> <input type="file" name="purchasereqs" id="file2" /> <h3>Bid Results</h3> <label for="file3">Filename:</label> <input type="file" name="bidresults" id="file3" /> <label for="file4">Filename:</label> <input type="file" name="bidresults" id="file4" /> <input type="submit" /> </form> 

Then you will have an action signature like this:

 [HttpPost] public ActionResult Create( TransactionViewModel model, IEnumerable<HttpPostedFileBase> purchasereqs, IEnumerable<HttpPostedFileBase> bidresults) { //save to database } 
+8
source

Source: https://habr.com/ru/post/910362/


All Articles