asp.net-mvc-3 – MVC3,多文件上传,模型绑定

可以更新复杂模型(Transaction).
复杂模型具有可以具有多个附件(文件)的属性,
这样用户可以在这种形式下同时上传多个文件,
我试图将这些文件保存到数据库中.

我已成功将多个文件发布到服务器,
关注博文
http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx.

但是为了保存这些文件,以便我可以跟踪哪些文件属于复杂模型(Transaction)的哪个对象,因此稍后在适当的位置显示它们,我需要一些方法将上传的文件关联到它所属的对象到,但由于所有文件都在名称’文件’下,我不知道如何使这项工作.

这是简化的复杂模型:

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

    public virtual PurchaseRequisition PurchaseRequisition { get; set; }

    public virtual Evaluation Evaluation { get; set; }
}

复杂模型的属性:

public class PurchaseRequisition
{
    [Key, ForeignKey("Transaction")]
    public int TransactionId { get; set; }

    public virtual Transaction Transaction { get; set; } 

    [Display(Name = "Specifications/Requisitioner's 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; }
}

这是控制器:

[HttpPost]
public ActionResult Create(TransactionViewModel model, IEnumerable<HttpPostedFileBase> files)
{ //save to database }
在视图中为采购申请和投标结果创建单独的部分.像这样的东西:

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

然后你会有这样的动作签名:

[HttpPost]
public ActionResult Create(
  TransactionViewModel model, 
  IEnumerable<HttpPostedFileBase> purchasereqs,
  IEnumerable<HttpPostedFileBase> bidresults)
{ 
   //save to database 
}
本站公众号
   欢迎关注本站公众号,获取更多程序园信息
开发小院