带附加数据的MVC多文件上载

时间:2014-01-14 21:49:50

标签: c# jquery asp.net-mvc model-view-controller file-upload

我已经能够通过以下方式成功地将多个文件发布到我的控制器:

http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/

然而, 我还试图在上传的每个文件中包含一些信息,用户必须输入这些信息,例如标题和版本

这是一个demo,可能会显示我想要实现的目标。

以下是我目前提出的处理问题in this way

这似乎不是正确的方式,因为我习惯将模型传递给控制器​​? 另一个问题是如果用户添加了三个文件上传但只选择了2个文件,那么它将不同步。

我做了一些搜索,似乎无法找到这样的例子。

1 个答案:

答案 0 :(得分:3)

首先创建2个ViewModels

public class NewViewModel 
{
    // list of files with additional data
    public List<UploadItem> UploadItems { get; set; }

    public string AnotherPropForView { get; set; }
}

public class UploadItem
{
    // your additional data
    public string CustomProp1  { get; set; }
    public string CustomProp2  { get; set; }
    // file
    public HttpPostedFileBase UpFile { get; set; }
}

创建控制器。一个用于显示空表单的操作,另一个用于从视图中查看过程数据。

public class SomeController : Controller 
{
    public ActionResult Create() 
    {
      NewViewModel model = new NewViewModel
      {
         // inicialize list
         UploadItems = new List<UploadItems> 
         {
            // inicialize empty objects ( if you want to have 2 file fields with additional data)
            // or inicialize only one object and another fields add by Javascript
            new UploadItem {},
            new UploadItem {},
         }
      }
      return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(NewViewModel model) 
    {
        // if (ModelState.IsValid) etc...
        foreach (var uploadItem in model.UploadItems)
        {
            // work with file and additional data
            var file = uploadItem.UpFile;
            var prop1 = uploadItem.CustomProp1;
            // file.SaveAs("/some/where"); atc ...
        }

        // return some view...
    }
}

创建视图

@model Path.To.NewViewModel
@using (Html.BeginForm("Create", "Some", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@* Print all inicialized upload items *@
  @for (int i = 0; i < Model.UploadItems.Count; i++)
  {
    @Html.TextBoxFor(model => model.UploadItems[@i].CustomProp1)
    @Html.TextBoxFor(model => model.UploadItems[@i].CustomProp2)
    <input type="file" id="UploadItems[@i].UpFile" name="UploadItems[@i].UpFile" />
  }

<button name="Action" type="submit" value="Save" class="btn">Save</button>
}

您可以使用Javascript动态添加Uploaditem到表单 - 您必须为输入中的名称和ID属性生成正确的索引