2

我想上传一个文件。我将 MVC3 与剃须刀一起使用。我有以下视图模型:

Public Class ImportL2EViewModel
    <Required(AllowEmptyStrings:=False, ErrorMessage:="L2E name required")>
    Public Property Name As String

    Public Property File As HttpPostedFileBase    
End Class

在我看来,我创建了一个表单:

@Using Html.BeginForm("Import", "L2ECreationWizard", FormMethod.Post, New Dictionary(Of String, Object) From {{"enctype", "multipart/form-data"}})
    @<div class="welcome-box acenter"> 
        <div style="display: block; text-align: left; width: 330px; margin: auto;">
            <div class="property">
                @Html.LabelFor(Function(m) m.Name)
                @Html.TextBoxFor(Function(m) m.Name)
            </div> 
            <div class="property">
                @Html.LabelFor(Function(m) m.File)
                @Html.TextBoxFor(Function(m) m.File, New With {.type = "file"})
            </div>            
        </div>
        <div class="actionBar">
            <a class="import fright button" href="#">Import</a>
        </div>
    </div>
End Using

生成的 html 如下所示:

<form method="post" enctype="multipart/form-data" action="/L2ECreationWizard/Import" novalidate="novalidate">
    <div class="welcome-box acenter"> 
        <div style="display: block; text-align: left; width: 330px; margin: auto;">
            <div class="property">
                <label for="Name">Name</label>
                <input type="text" value="" name="Name" id="Name" data-val-required="L2E name required" data-val="true">
            </div> 
            <div class="property">
                <label for="File">File</label>
                <input type="file" value="" name="File" id="File">
            </div>            
        </div>
        <div class="actionBar">
            <a href="#" class="import fright button">Import</a>
        </div>
    </div>
</form>

我将表单发布到以下操作方法:

<HttpPost()>
Function Import(vm As ImportL2EViewModel) As ActionResult
    ' Nothing yet
End Function

发布后我可以看到vm.Name填写,但是。 是。我究竟做错了什么?我在 SO 上看到过类似的问题,但对我没有任何帮助。我搞不清楚了...vm.FileNothingRequest.Files.Count0

4

1 回答 1

2

将参数添加到您的方法中,HttpPostedFileBase file如下所示:

<HttpPost()>
Function Import(vm As ImportL2EViewModel, file As HttpPostedFileBase) As ActionResult

Dim fileName = Path.GetFileName(file.FileName)
    Dim physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName)

    // The files are not actually saved in this demo
    // file.SaveAs(physicalPath)
    ...
End Function

并从您的模型中删除 HttpPostedFileBase 属性。它是 Request 对象的一部分,因此无法添加到您的模型中。

如果您允许选择多个文件,那么这就是您需要能够遍历上传的每个文件

<HttpPost()>
Function Import(vm As ImportL2EViewModel, attachments As IEnumerable(Of HttpPostedFileBase)) As ActionResult

    For Each file As var In attachments
        Dim fileName = Path.GetFileName(file.FileName)
        Dim physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName)
        ' The files are not actually saved in this demo
        ' file.SaveAs(physicalPath);
    Next
    ...
End Function
于 2012-05-21T14:32:10.883 回答