I have a form with four fields with one being of type file field. I also have a team with the following properties:
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; }
I created a ViewModel with the following properties so as to enable file upload and to validate the properties.
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; }
}
I have a customized data annotation validator for uploading file
// 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;
}
}
In my controller, I made use of the TeamVM by using a HttpGet request to make the TeamVM model available for use.
[HttpGet]
public ActionResult Create()
{
TeamVM model = new TeamVM();
return View(model);
}
I then used the model in the Create Action of the TeamVM as shown below:
[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");
}
}
But I get the error in the following portion of the code:
team objTeam = new team
{
teamName = model.TeamName,
teamPicture = path,
description = model.Description,
content = model.Content
};
I don't know what is coursing the DbEntityValidationException error. Your help will be appreciated.