Request.Files在mvc中按名称命名

时间:2016-01-07 13:26:55

标签: c# asp.net-mvc razor

我传入一个文件名,然后我想要request.files但它一直返回null。这是代码:

 @using (Html.BeginForm("AddTechNote", "Ticket", FormMethod.Post))
 <div class="col-md-10">
       <input type="file" id="fileToUpload" name="fileToUpload" />
       <span class="field-validation-error" id="spanfile"></span>
 </div>

并在控制器中:

public ActionResult AddTechNote(TicketView ticketReturn, string Note, bool PublicNote, string fileToUpload, string CopyIntoEmail)
{
        HttpPostedFileBase file = Request.Files[fileToUpload];
        string _fileName = null;

        if (file != null && file.ContentLength > 0)
        {
               _fileName = new FileController().UploadFile(file, "Tickets", ticketReturn.TicketNumber.ToString());
        }

视图不是强类型的(至少不是这个模型)。输入字段位于表单内。

1 个答案:

答案 0 :(得分:0)

您需要拥有string fileToUpload并在后续代码中使用HttpPostedFileBase fileToUpload,而不是fileToUpload,如下所示。

public ActionResult AddTechNote(TicketView ticketReturn, string Note, bool PublicNote, HttpPostedFileBase fileToUpload, string CopyIntoEmail)
{
        string _fileName = null;

        if (fileToUpload != null && fileToUpload.ContentLength > 0)
        {
               _fileName = new FileController().UploadFile(fileToUpload, "Tickets", ticketReturn.TicketNumber.ToString());
        }
  ...........
}

另外,请确保为multipart/form-data设置了BeginForm,例如 -

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))