0

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.

Guzzyman
  • 561
  • 6
  • 16
  • 37
  • in VS check the setting "Break on all exceptions" then you can inspect the real message contained inside the `DbEntityValidationException`. Take a look here for more info about troubleshooting http://stackoverflow.com/a/15820506/61577 – cleftheris Oct 13 '15 at 10:26
  • Also keep in mind that the "real" error is always hidden in the `EntityValidationErrors` collection and not the exception message itself. – cleftheris Oct 13 '15 at 10:28
  • can u tell me objBs.teamBs.Insert(objTeam); throws exception – Manraj Oct 13 '15 at 10:30
  • @Manraj: Yes objBs.teamBs.Insert(ojbTeam); throws exception – Guzzyman Oct 13 '15 at 12:01
  • then you have to do migrations if you are using code first – Manraj Oct 13 '15 at 12:12
  • @Manraj: I use DataBase First. I generated my entities from the database. – Guzzyman Oct 13 '15 at 12:27

1 Answers1

1

this i will help

catch (DbEntityValidationException dbEx)
{
    var sb = new StringBuilder();
    foreach (var validationErrors in dbEx.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            sb.AppendLine(string.Format("Entity:'{0}' Property: '{1}' Error: '{2}'",
                              validationErrors.Entry.Entity.GetType().FullName,
                              validationError.PropertyName,
                              validationError.ErrorMessage));
        }
    }
    throw new Exception(string.Format("Failed saving data: '{0}'", sb.ToString()), dbEx);
}

also you need

ModelState.IsValid

e.g

  try
  {

     if (ModelState.IsValid)
     {
           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");
       }

       //the view model is NOT valid
       return View(model)

   }
   catch (DbEntityValidationException dbEx)
   {
       var sb = new StringBuilder();
       foreach (var validationErrors in dbEx.EntityValidationErrors)
       {
            foreach (var validationError in validationErrors.ValidationErrors)
            {
                sb.AppendLine(string.Format("Entity:'{0}' Property: '{1}' Error: '{2}'",
                              validationErrors.Entry.Entity.GetType().FullName,
                              validationError.PropertyName,
                              validationError.ErrorMessage));
             }
       }
                  //throw new Exception(string.Format("Failed saving data: '{0}'", sb.ToString()), dbEx);

            TempData["Msg"] = sb.ToString();
            return RedirectToAction("Index");
    }

update

change your Team entity class like so, remember to change the DB as well... but i believe you have already done this...

The default without an annotation is 50, google this for more info

public class Team 
{
    public int teamID { get; set; }
    public string teamName { get; set; }
    [MaxLength]
    public string teamPicture { get; set; }
    public string description { get; set; }
    public string content { get; set; }
}
Seabizkit
  • 2,417
  • 2
  • 15
  • 32
  • Thanks for your response. It actually displayed this error after using your chunk of code. sb = {Entity:'BOL.team' Property: 'teamPicture' Error: 'The field teamPicture must be a string or array type with a maximum length of '50'.' } Now, teamPicture in the database is of the type string. I have changed the string length the nVarChar(Max). I still have the same error. What can I do now? – Guzzyman Oct 13 '15 at 12:57
  • have you change 'teamPicture' in the code '[MaxLength(500)]' on the entity.... eg search for Entity:'BOL.team and check the code around that. ie must be string and have a '[MaxLength()]' set. Are you using code first? do you have MaxLength on your properties or are you using mapping to configure.... – Seabizkit Oct 13 '15 at 13:28
  • I have this error after using the [MaxLength(500)]. Unable to cast object of type 'System.Web.HttpPostedFileWrapper' to type 'System.Array' – Guzzyman Oct 13 '15 at 14:06
  • OK but i believe this answers your question? would that not be a new Question? I don't mind helping but... its shifted from the original, which I have answered, anyway on what line are you getting that error...? – Seabizkit Oct 13 '15 at 14:23
  • just for kicks take "[Required(ErrorMessage = "Please Upload Team Picture")]" off "public HttpPostedFileBase TeamPicture { get; set; }" as it would not make sense to me. – Seabizkit Oct 13 '15 at 14:28
  • This has been resolved. I had to delete the edmx fand regenerated another one from the database. This time around, my database filed had been set to nvarchar(Max), then I had a teamValidation class where I added the data annotation MaxLength(500). – Guzzyman Oct 13 '15 at 14:28
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/92155/discussion-between-guzzyman-and-seabizkit). – Guzzyman Oct 13 '15 at 14:30