File upload bound to the Viewmodel

前端 未结 2 1282
南方客
南方客 2020-12-16 20:57

I have a form where I am uploading multiple files and there are a couple of textboxes and some checkboxes associated with each file being uploaded. I have seen examples for

相关标签:
2条回答
  • 2020-12-16 21:05

    The fix to this is changing the way you Name and ID the upload control.

    <%: Html.TextBoxFor(model => model.EmpName, new { maxLength = 50 })%>
    
    Upload your files here: 
    <input type="file" id="FileUploadPackets[0].UpFile" name="FileUploadPackets[0].UpFile" value="ActionHandlerForForm"  />
    <%: Html.TextBoxFor(model => model.FileUploadPackets[0].UserEnteredDesc )%>
    
    <input type="file" id="FileUploadPackets[1].UpFile" name="FileUploadPackets[1].UpFile" value="ActionHandlerForForm"  />
    <%: Html.TextBoxFor(model => model.FileUploadPackets[1].UserEnteredDesc )%>
    

    This worked for me!! Hope it helps anyone else out there..

    0 讨论(0)
  • 2020-12-16 21:23

    GetHtml helper is not part of mvc framework, you should look up for third party library containing that helper.

    Uploading file that is part of ViewModel is simple though. Basically it goes like this

    Define view model

    public class MyViewModel 
    {
         public HttpPostedFileBase MyFile { get; set; }
    }
    

    Inside Views/Shared/EditorTemplates, create MyViewModel.cshtml

    <input type="file" id="MyFile" name="MyFile" />
    

    And view, corresponding to upload action

    @model MyViewModel
    
    @using(Html.BeginForm("Upload", "MyController", FormMethod.Post, new { enctype="multipart/form-data"})
    {
         @Html.EditorForModel()
        <input type="submit" value="Upload" />
    }
    

    required attribute is important to upload files.

    And that's it, once form is submitted, you should see uploaded file inside [HttpPost] action, vm.MyFile.

    0 讨论(0)
提交回复
热议问题