在Razor表单视图中包含文件上载

时间:2011-12-09 18:34:43

标签: asp.net-mvc vb.net asp.net-mvc-3

MVC 3,VB.NET。我的应用程序中有一个表单,可以从用户那里获取基本信息,然后允许他们上传简历。我现在通过使用重定向到另一种形式来实现这一目的,唯一的目的是选择要上传的文件,然后提交它。我认为邋..我试过从同一个表单但是文件是在提交时丢失..虽然我不确定它,但我相信这是因为我没有在表单中使用正确的语法来处理文件...下面是View到目前为止然后控制器发布函数.. < / p>

@ModelType xxxxxxxx.courseproposal
@Code
ViewData("Title") = "Course Proposal"
End Code
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript">         </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@Using Html.BeginForm()
@Html.ValidationSummary(True)
@<fieldset>
 <table>
    <tr>
        <th>Presenter 1</th>
    </tr>

    <tr>
        <td>First Name</td>
        <td>Last Name</td>
        <td>Title</td>
        <td>Phone Number</td>
        <td>Email Address</td>

    </tr>
    <tr>
        <th>@Html.EditorFor(Function(model) model.Name_First1) @Html.ValidationMessageFor(Function(model) model.Name_First1)</th>
        <th>@Html.EditorFor(Function(model) model.Name_Last1) @Html.ValidationMessageFor(Function(model) model.Name_Last1)</th>
        <th>@Html.EditorFor(Function(model) model.Title_1) @Html.ValidationMessageFor(Function(model) model.Title_1)</th>
        <th>@Html.EditorFor(Function(model) model.phone_number1) @Html.ValidationMessageFor(Function(model) model.phone_number1)</th>
        <th>@Html.EditorFor(Function(model) model.email_address1) @Html.ValidationMessageFor(Function(model) model.email_address1)</th>
         <th>@Html.Label("file","Filename:")<input type="file" name="file" id="file" />  </th>
    </tr>
</table> 

<div id="sidebar3">

 <p>
 <input type="submit" value="Submit Course Proposal" />
 </p>

 <p>
 @Html.ActionLink("Back to List", "Index")
 </p>
 </div>

</fieldset>
End Using

帖子功能是这样的:

   <AcceptVerbs(HttpVerbs.Post)>
    Function CourseProposal(ByVal courseprop As courseproposal) As ActionResult
        courseprop.conf_Number = _AnnualNumber
        db.courseproposals.AddObject(courseprop)
        db.SaveChanges()
        _id = courseprop.idCourseProposal
        Dim _filename As String = String.Empty
        For Each File As String In Request.Files
            Dim hpf As HttpPostedFileBase = TryCast(Request.Files(File), HttpPostedFileBase)
            If hpf.ContentLength = 0 Then
                Continue For
            End If
            Dim savedfileName As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CoursePropResumes\" + Path.GetFileName(hpf.FileName)
            hpf.SaveAs(savedfileName)
            _filename = hpf.FileName
        Next

1 个答案:

答案 0 :(得分:4)

您的表单需要enctype="multipart/form-data"

尝试

Html.BeginForm(null, null, FormMethod.Post, new { enctype="multipart/form-data"})

编辑:这当然是针对C#的。在VB中应该读取

Html.BeginForm(Nothing, Nothing, FormMethod.Post, New With { .enctype="multipart/form-data"})