【发布时间】:2016-12-08 12:39:30
【问题描述】:
我正在尝试在我的应用程序中上传文件。我在我的模型中使用了HttpPostedFileBase 和一个byte[] 数组,但不知道为什么在我运行我的应用程序时会显示此错误。下面我还上传了运行应用程序时显示的错误的image。
显示的错误是:
在模型生成过程中检测到一个或多个验证错误:
AdSite.Models.HttpPostedFileBase: :
EntityType 'HttpPostedFileBase' has no key defined. Define the key for this EntityType.HttpPostedFileBases: EntityType: EntitySet 'HttpPostedFileBases' 基于没有定义键的类型'HttpPostedFileBase'。`
我的模特:
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>
【问题讨论】:
-
在“绑定”属性中,您可以定义“专辑”的属性。 'File' 属性从何而来?
-
您好@SRQCoder,
File属性在Model class中定义。它的类型为HttpPostedFileBase File。你可以在这里看到我的模型类。 -
您需要从数据模型中删除
public HttpPostedFileBase File { get; set; }(它是一个复杂的对象,不能存储在数据库列中)。您编辑数据,所以使用视图模型,视图模型将包含该属性(而不是public byte[] ImageData { get; set; }属性 - What is ViewModel in MVC?
标签: c# asp.net asp.net-mvc asp.net-mvc-4 httppostedfilebase