MVC HttpPost无法正常工作

时间:2012-06-13 02:41:44

标签: c# asp.net-mvc

我在执行此代码时有一个空对象引用异常。我有一个文件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的数据,但文件引用了null对象。可能是什么问题?

1 个答案:

答案 0 :(得分:4)

上传实际上要求您在表单上指定enctype属性。以下是如何执行此操作的示例:

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