I want to have a page on my website where I can upload files. For each file I want to have a name and a category.
[Required(ErrorMessage = "Please choose a file")]
[Display(Name = "File")]
public HttpPostedFileBase file { get; set; }
[Required(ErrorMessage = "A name is required")]
[Display(Name = "Name")]
public string name { get; set; }
[Display(Name ="Category")]
public string cat { get; set; }
This is my model. I want to have some dynamic form, what I mean is a form with a button that allows the user to add another form on the page to upload multiple files with a name and a category for each file. I've done this with Symfony2, but I have no idea how to do it with ASP.NET. Can someone help me please ?
The following is a bare minimum example based on this blogpost. For demo purposes, I've named my model
Foo
. So whenever you read this, this should be your model with file, name and cat properties.First, add
https://www.nuget.org/packages/BeginCollectionItem/
to your project.Then, add a partial view to your Views folder. I've named mine "_AddFile.cshtml":
Note, the
Html.BeginCollectionItem("files")
, this is creating a collection, that is later grouped together and bound to your model named "files".Our controller looks like this:
In your view, use this form:
The foreach loop renders a partial View for each model entry, in our case just one with a default entry.
The javascript loop then calls our PartialView and renders an empty template below the existing ones.
A call to submit, then lets you deal with your files in any way you want:
At first create another model like following:
Then in the razor view create form like this way:
Now create a controller action method to accept the fileList: