2016-12-08 39 views
0

我試圖在我的應用程序中上傳文件。我在我的模型和byte[]數組中使用了HttpPostedFileBase,但不知道爲什麼當我運行我的應用程序時顯示此錯誤。下面我也上傳了運行應用程序時顯示的錯誤的image如何在Asp.net MVC 5應用程序中上傳文件

被示出的錯誤是:模型生成過程中檢測到

一個或多個驗證錯誤:

AdSite.Models.HttpPostedFileBase:EntityType 'HttpPostedFileBase' has no key defined. Define the key for this EntityType. HttpPostedFileBases:的EntityType:EntitySet的 'HttpPostedFileBases' 是基礎型 'HttpPostedFileBase' 有沒有鍵defined.`

Error screenshot

我的模型:

public class Album 
{ 
    [Key] 
    public int Id { get; set; } 
    public string ProductTitle { get; set; } 
    public string Description { get; set; } 
    public string ImageFileName { get; set; } 
    public int ImageSize { get; set; } 
    public byte[] ImageData { get; set; } 
    [Required(ErrorMessage="Please select image file.")] 
    public HttpPostedFileBase File { get; set; }   
} 

我的控制器代碼:

public ActionResult Upload([Bind(Include = "Id,ProductTitle,Description,ImageFileName,ImageData,File,ImageSize")]Album album) 
{ 
    if (ModelState.IsValid) 
    { 
     // album.ImageFileName = album.File.FileName; 
     // album.ImageSize = album.File.ContentLength; 

     byte[] data = new byte[album.File.InputStream.Length]; 
     album.File.InputStream.Read(data, 0, data.Length); 
     album.ImageData = data; 

     var db = new AlbumContext(); 
     db.Albums.Add(album); 
     db.SaveChanges(); 

     return RedirectToAction("Index"); 
    } 
    return View(album); 
} 

我的視圖代碼:

<div class="form-group"> 
    <label class="control-label col-md-2">Select Image:</label> 
    <div class="col-md-10"> 
     @Html.TextBoxFor(model=>model.File, new { type="file"}) 
     @Html.ValidationMessage("CustomError") 
    </div> 
</div> 
+0

在'綁定'屬性中,您可以爲'相冊'定義屬性。 '文件'屬性來自哪裏? –

+0

Hello @SRQCoder,'File'屬性在'Model class'中定義。它的類型是'HttpPostedFileBase File'。你可以在這裏看到我的模型課。 –

+0

你需要刪除'public HttpPostedFileBase File {get;組; }'從你的數據模型(它是一個複雜的對象,不能存儲在數據庫列中)。你編輯數據,所以使用視圖模型和視圖模型將包含該屬性(而不是'公共字節[] ImageData {get; set;}'屬性 - [什麼是MVC中的ViewModel?](http:// stackoverflow。 com/questions/11064316/what-is-viewmodel-in-mvc) –

回答

0

這就是爲什麼要使用模型來獲取數據,然後轉換它給你的DTO對象。

的錯誤是因爲你想給System.Web.HttpPostedFileBase類存儲到數據庫中。這不是你要控制的類,它不是直接存儲在數據庫中的。在這種情況下,HttpPostedFileBase是您的「模型」。

創建另一個對象,並將其綁定到你的DbContext來存儲你需要了解你的數據庫文件的內容。不要只是在那裏扔東西。

+0

謝謝。但你能給我看一個這裏的代碼示例嗎? –

+0

你是不是要爲其他信息創建一個新的「模型類」這需要上傳的?這是我需要兩類,一爲HttpPostedFileBase財產和一個用於其他財產?? –

+0

我的意思是創建你'HttpPostedFileBase'需要的任何信息一DTO類。 – krillgar