编程语言
首页 > 编程语言> > c#-使用HttpPostedFileBase的强类型模型无法支持视图

c#-使用HttpPostedFileBase的强类型模型无法支持视图

作者:互联网

我希望有人可以帮助我.

我正在使用VS 2012和MVC4.

我正在使用使用HttpPostedFileBase的强类型模型测试项目.当我尝试对视图进行脚手架操作时,它失败并显示:

---------------------------
Microsoft Visual Studio
---------------------------
Unable to retrieve metadata for 'ImageTest.Models.ImageHandler'. Value cannot be null.

Parameter name: key
---------------------------
OK   
---------------------------

我尝试按照网络上的一些帖子中的建议先卸载然后重新安装MVC,但这无济于事.这是我的模型:(是,我已经在ID上尝试了[Key],但没有区别)

using System;
using System.Web;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace ImageTest.Models
{
public class ImageHandler
{
public int Id { get; set; }
public string ImageName { get; set; }
public HttpPostedFileBase File { get; set; }
}
}

我认为这可能是一个上下文问题,但是无论我创建自定义上下文还是使用预定义的上下文都不会出现相同的错误.这是预定义的上下文:

using ImageTest.Models;
using System.Data.Entity;

public class ImageHandlerContext : DbContext
{
public ImageHandlerContext() : base("DefaultConnection")
{
}

public DbSet<ImageHandler> ImageHandler { get; set; }
}

作为测试,如果我注释掉:

// public HttpPostedFileBase File { get; set; }

我可以毫无问题地支撑View.这是错误吗?我在任何地方都看不到不支持Scaffolding HttpPostedFileBase的文档.查看:HttpPostedFileBase

提前致谢.

解决方法:

斯坦走在正确的轨道上.

模型视图控制器或MVC使用实体框架来支持视图.

Entity Data Model: Primitive Data Types

除非定义了复杂数据类型,否则.NET 4.5当前支持基本数据类型.以下是受支持的原始数据类型:

Binary
Boolean
Byte
DateTime
DateTimeOffset
Decimal
Double
Float
Guid
Int16
Int32
Int64
SByte
String
Time

有关扩展此功能的更多信息,请参见:Complex Type.

谢谢Stan竖起大拇指.

编辑:首先需要使用原始数据类型来构建视图的支架,然后将HttpPostedFileBase添加到模型中以使用文件上传功能.例如:Upload Image in form and show it on MVC 4

另外,您将需要在模型中使用(NotMapped):

[NotMapped]
public HttpPostedFileBase File { get; set; }

现在,在“脚手架创建ActionResult方法”中,视图的“表单返回值”包含可以使用的System.Web.HttpPostedFileWrapper.

简短答案:

1: Create your Code First Model with Primitive Data Types only! Unless you use the [NotMapped] Attribute.
2: Scaffold your View's.
3: If not done so in step 1, Add to your Model the Methods needed.  E.G: public HttpPostedFileBase File { get; set; } using the [NotMapped] Attribute
4: Add to your Database the necessary Table either manually or from the Console.
5: Add the necessary code to your View's and Controller.

那应该足以让您工作…

标签:asp-net-mvc-4,c
来源: https://codeday.me/bug/20191123/2065400.html