ASP.NET MVC3 Download the file from the partial view (and fill in the corresponding field in the model)

I know that the topic has already been discussed in SO and elsewhere, but I can not find the answer to my question.



I am working on an ASP.NET MVC3 project and I would like to create a partial view containing FileUpload. This partial view is called up on the base page Create, and I want the file to upload to belong to the model being created. Only when the user submits the form, the selected file will be uploaded.

Here is the explanation for the code:


Model ModelToCreate

public class ModelToCreate
{
    //Some properties

    public FileUploadModel Files { get; set; }
}


Model FileUploadModel

public class FileUploadModel
{
    public IEnumerable<HttpPostedFileBase> Files { get; set; }
}


My PartialView (_UploadFiles.cshtml)

@model Models.ModelToCreate

//I tried with Html.BeginForm(Create, MyController instead of null, null, but with no result.
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(m => m.Files, new { type = "file", name = "Files" })
}


How a partial view is called (by Create.cshtml)

@Html.Partial("_UploadFiles")

@Html.Partial("_UploadFiles", Model), ...



Submit Create.cshtml, . BUT Files null, .



- ? , ( ?)
!



( )

, Create.cshtml :

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "target-form" }))
{
    // Some fields, Textboxes and others CheckBoxes

    //Call to partial View
}

, <form>... <tag> <tag>, "".

BeginForm Create.cshtml:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "target-form", enctype = "multipart/form-data" }))

@Html.Partial("_UploadFiles", Model)
+3
1

, .

Create.cshtml ( )

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

_UploadFiles.cshtml

@model ModelToCreate

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

( , FileUploadModel).

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

:

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);
}

enter image description here

+4

All Articles