I know the subject has already been discussed on SO and elsewhere, but I can't find any answer to my question.
I'm working on an ASP.NET MVC3 project, and I'd like to create a Partial view containing a FileUpload
. This partial view is called on a basic Create
page, and I'd like the file to upload belongs to the model to create. It is only when the user will submit the form the selected file will be uploaded.
Here is an explanation by 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 the partial view is called (by Create.cshtml)
@Html.Partial("_UploadFiles")
I also tried with @Html.Partial("_UploadFiles", Model)
, but with no result...
When I click the Submit
button in Create.cshtml
, the form is submitted to my controller BUT Files
field is always null
whereas the other datas are OK.
Am I missing something ? Could you indicate my where (and why ?)
Thank you !
UPDATE (and Solution)
Here is some additionnal information I forgot about Create.cshtml
The form look like this :
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "target-form" }))
{
// Some fields, Textboxes and others CheckBoxes
//Call to partial View
}
When I take a look to generated source code, I see the partial view in a <form>
tag... So I have a <tag>
in a <tag>
, which is illegal and "ignored". This causes the problem
SOLUTION Just add this tag to the BeginForm of Create.cshtml
:
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "target-form", enctype = "multipart/form-data" }))
and call my Partial View as
@Html.Partial("_UploadFiles", Model)