mvc upload file with model - second parameter posted file is null

后端 未结 4 1297
南旧
南旧 2020-12-05 13:35

I have a simple model with 1 string property which I render on a simple view.

the view looks like the following:

@using (Html.BeginForm(\"UploadFile\         


        
4条回答
  •  余生分开走
    2020-12-05 14:23

    For dealing with a single file input you can define a HttpPostedFileBase property within the ViewModel:

    public class SomeModel() 
    { 
        public SomeModel() 
        {
        }
    
        public HttpPostedFileBase SomeFile { get; set; }
    }
    

    And then implement it in the following way:

    View:

    @model SomeModel

    @using (Html.BeginForm(
        "Submit", 
        "Home", 
        FormMethod.Post, 
        new { enctype="multipart/form-data" }))
    {
        @Html.TextBoxFor(m => m.SomeFile, new { type = "file" })
        
    }
    

    Controller:

    [HttpPost]
    public ActionResult Submit(SomeModel model)
    {
        // do something with model.SomeFile
    
        return View();
    }
    

    In case you need to deal with multiple files, you can either:

    • create multiple properties and implement them separately just like the one above;
    • change the public HttpPostedFileBase SomeFile property to something like public List SomeFiles and then span multiple @Html.TextBoxFor(m => m.SomeFile, new { type = "file" }) controls to have them all within that list.

    In case you need additional info check out this blog post that I wrote on the topic.

提交回复
热议问题