【发布时间】:2015-10-13 10:20:02
【问题描述】:
我有一个包含四个字段的表单,其中一个是文件字段类型。我还有一个具有以下属性的团队:
public int teamID { get; set; }
public string teamName { get; set; }
public string teamPicture { get; set; }
public string description { get; set; }
public string content { get; set; }
我创建了一个具有以下属性的 ViewModel,以便启用文件上传并验证属性。
public class TeamVM
{
[Required(ErrorMessage = "Please Enter Your Team Name")]
[Display(Name = "Team Name")]
public string TeamName { get; set; }
[DisplayName("Team Picture")]
[Required(ErrorMessage = "Please Upload Team Picture")]
[ValidateFile]
public HttpPostedFileBase TeamPicture { get; set; }
[Required]
[Display(Name = "Description")]
public string Description { get; set; }
[Required(ErrorMessage = "Please Enter Team Content")]
[Display(Name = "Contenting")]
[MaxLength(500)]
public string Content { get; set; }
}
我有一个用于上传文件的自定义数据注释验证器
// Customized data annotation validator for uploading file
public class ValidateFileAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
int MaxContentLength = 1024 * 1024 * 3; //3 MB
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png" };
var file = value as HttpPostedFileBase;
if (file == null)
return false;
else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ErrorMessage = "Please upload Your Photo of type: " + string.Join(", ", AllowedFileExtensions);
return false;
}
else if (file.ContentLength > MaxContentLength)
{
ErrorMessage = "Your Photo is too large, maximum allowed size is : " + (MaxContentLength / 1024).ToString() + "MB";
return false;
}
else
return true;
}
}
在我的控制器中,我通过使用 HttpGet 请求来使用 TeamVM,以使 TeamVM 模型可供使用。
[HttpGet]
public ActionResult Create()
{
TeamVM model = new TeamVM();
return View(model);
}
然后我在 TeamVM 的 Create Action 中使用了该模型,如下所示:
[HttpPost]
public ActionResult Create(TeamVM model)
{
try
{
var fileName = Path.GetFileName(model.TeamPicture.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
model.TeamPicture.SaveAs(path);
team objTeam = new team
{
teamName = model.TeamName,
teamPicture = path,
description = model.Description,
content = model.Content
};
objBs.teamBs.Insert(objTeam);
TempData["Msg"] = "Created Successfully!";
return RedirectToAction("Index");
}
catch (DbEntityValidationException e1)
{
TempData["Msg"] = "Create Failed! :" + e1.Message;
return RedirectToAction("Index");
}
}
但我在以下代码部分中收到错误:
team objTeam = new team
{
teamName = model.TeamName,
teamPicture = path,
description = model.Description,
content = model.Content
};
我不知道是什么导致了 DbEntityValidationException 错误。您的帮助将不胜感激。
【问题讨论】:
-
在 VS 中检查设置“中断所有异常”,然后您可以检查
DbEntityValidationException中包含的真实消息。在此处查看有关故障排除的更多信息stackoverflow.com/a/15820506/61577 -
另外请记住,“真正的”错误始终隐藏在
EntityValidationErrors集合中,而不是异常消息本身。 -
你能告诉我 objBs.teamBs.Insert(objTeam);抛出异常
-
@Manraj: 是的 objBs.teamBs.Insert(ojbTeam);抛出异常
-
如果你首先使用代码,你必须进行迁移
标签: c# asp.net asp.net-mvc asp.net-mvc-4