Skip to main content
 首页 » 编程设计

c#之MVC HttpPost 不工作

2024年02月20日23kuangbin

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

请您参考如下方法:

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

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