1

在执行此代码时,我有一个空对象引用异常。我有一个文件 html 控件,我的 Razor 代码如下所示:

@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 和 description 的数据,但文件引用了一个空对象。可能是什么问题呢?

4

1 回答 1

4

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

@using (Html.BeginForm("AddFiles", "AdministerFiles", FormMethod.Post, 
    new { enctype = "multipart/form-data" }))
{ 
   ...
}
于 2012-06-13T02:54:31.570 回答