我試圖在我的應用程序中上傳文件。我在我的模型和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.`
我的模型:
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>
在'綁定'屬性中,您可以爲'相冊'定義屬性。 '文件'屬性來自哪裏? –
Hello @SRQCoder,'File'屬性在'Model class'中定義。它的類型是'HttpPostedFileBase File'。你可以在這裏看到我的模型課。 –
你需要刪除'public HttpPostedFileBase File {get;組; }'從你的數據模型(它是一個複雜的對象,不能存儲在數據庫列中)。你編輯數據,所以使用視圖模型和視圖模型將包含該屬性(而不是'公共字節[] ImageData {get; set;}'屬性 - [什麼是MVC中的ViewModel?](http:// stackoverflow。 com/questions/11064316/what-is-viewmodel-in-mvc) –