ASP.NET MVC3 Upload a file from a Partial view (and fill the corresponding field in the Model)

僤鯓⒐⒋嵵緔 提交于 2019-12-06 03:19:21

Ok, this will get it working for you.

Create.cshtml View (With the form & submit moved outside of the partial)

@using(Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
   @Html.Partial("_UploadFiles", Model)
   <input type="submit" value="submit" />
}

_UploadFiles.cshtml view

@model ModelToCreate

@Html.TextBoxFor(m => m.Files.Files, new { type = "file", name = "Files" })

Models (Changed to a List and also note the initializer in the FileUploadModel constructor).

public class ModelToCreate
{
    //Some properties
    public FileUploadModel Files { get; set; }
}

public class FileUploadModel
{
   public FileUploadModel()
   {
        Files = new List<HttpPostedFileBase>();
   }

   public List<HttpPostedFileBase> Files { get; set; }
}

Controller actions:

public ActionResult Create()
{
    var model = new ModelToCreate();

    return View(model);

}

[HttpPost]
public ActionResult Create(ModelToCreate model)
{
   var file = model.Files.Files[0];
   return View(model);
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!