Upload multiple files in one form MVC4

后端 未结 3 990
南笙
南笙 2021-02-04 13:42

I\'m trying to upload multiple images on one form

@using (Html.BeginForm(\"Create\", \"AdminRestaurants\", FormMethod.Post, new { enctype = \"multipart/form-data         


        
3条回答
  •  误落风尘
    2021-02-04 14:09

    Your problem is that you form creates a post request with information that the model binder can bind because the naming convention is not right.

    you see, you have 4 file fields each with a different name, for the model binder to bind them correctly your controller action signature should look like this:

    public ActionResult Create(HttpPostedFileBase mgmFile, 
                               HttpPostedFileBase logoFile, 
                               HttpPostedFileBase fohFile ,
                               HttpPostedFileBase bohFile)
    

    Following MCV design pattern The best option would be to use a ViewModel that holds an IEnumerable and you would create a custom editor template for an IEnumerable

    so that you could use it like that:

    Html.EditorFor(m=>Model.filesUploaded)
    

    and your controller action would look like this:

    public ActionResult Create(MyViewModel i_InputModel)
    {
        i_InputModel.filesUploade; //Use the files here to upload them.
    }
    

    Other options are: Use the HTML5 multiple attribute on the file input field like this:

    
    

    and a controller action like this:

    public ActionResult Create(HttpPostedFileBase files)
    

    or use multiple file fields but index them in their name:

    
    
    
    
    

    and then you could use a controller action like this:

    public ActionResult Create(IEnumerable files)
    

提交回复
热议问题