2012-06-13 273 views
1

我在执行此代码时有一个空对象引用异常。我有一个文件,HTML控件和我的剃刀代码如下所示:MVC HttpPost不工作​​

@using (Html.BeginForm("AddFiles", "AdministerFiles", FormMethod.Post)) 
{ 
    <p><label for="filename">Filename : </label><input type="text" name="filename" /></p> 
    <p><label for="description">Description : </label><input type="text" name="description" /></p> 
    <p><input type="file" name="file" id="file" /> </p> 
    <p><input type="hidden" value="@Model[2]" name="catid"/></p> 

    <input type="submit" value="Upload Now!" /> 
    <input type="reset" value="Reset" /> 
}  

我AdministerFilesController是这样的:

[HttpPost] 
    public ActionResult AddFiles(HttpPostedFileBase file, int catid, string description) 
    { 
     // Verify that the user selected a file { 
     if (file != null && file.ContentLength > 0) 
     { 
      // extract only the filename 
      var filename = Path.GetFileName(file.FileName); 
      // store the file inside ~/App_Data/Uploads folder 
      var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), filename); 
      file.SaveAs(path); 
     } 
     RefDataLinks_mst fileDetails = new RefDataLinks_mst() 
     { 
      LastModified = new DateTime(2012,1,1), 
      CategoryID = catid, 
      DataFileName = Path.GetFileName(file.FileName), 
      DataTitle = "SAMPLETITLE", 
      DataID = ((new Random()).Next(100, 1000)), 
      DataFilePath = "Sample/Path", 
      Description = description, 
      UpdatedBy = "Arjel", 
      FileSize = file.ContentLength 
     }; 
     bool b = ServiceReferenceHelper.AddFile(fileDetails); 
     // Redirect back to the index action to show the form once again 
     return Redirect("AddFiles?catid=" + catid); //both works 
     //return RedirectToAction("ViewDataFiles", new { catid = catid }); 
    } 

从CATID和说明接收到的数据,但为空对象的文件引用。可能是什么问题呢?

回答

4

上传实际上要求您在表单上指定enctype属性。这里有一个如何做到这一点的例子:

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