2017-01-29 1 views
0

Salut tout le monde donc j'essaye de créer une application en utilisant asp.net mvc avec une base de données de code d'abord qui permet aux utilisateurs de pouvoir créer un blog avec autant d'images que ils espèrent. L'application fonctionne parfaitement tant que la tête, le corps et l'image sont pleins ou si je prends la validation de la tête et du corps. Le problème est que si j'ai une validation sur la tête et le corps, le programme plante avec cette erreur de validation:autres entrées validation interférant avec entrée qui devrait permettre null

DbEntityValidationException An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in Crud.dll but was not handled in user code

Additional information: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. The validation errors are: Heading is Required; Body is Required

Merci pour votre aide sur ce problème.

Voir

@model Crud.Models.PostModel 
@{ 
    ViewBag.Title = "Create"; 
} 
<h2>Create</h2> 
@using (Html.BeginForm("Edit", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 
    <fieldset> 
     <div class="editor-field"> 
      @Html.LabelFor(model => model.Heading) 
      @Html.TextBoxFor(model => model.Heading) 
      @Html.ValidationMessageFor(model => model.Heading) 
     </div> 
     <div> 
      @Html.LabelFor(model => model.PostBody) 
      @Html.TextBoxFor(model => model.PostBody) 
      @Html.ValidationMessageFor(model => model.PostBody) 
     </div> 
     <div class="editor-label"> 
      @*Temporary way to upload*@ 
      @Html.LabelFor(model => model.ImagePath) 
      @Html.TextBoxFor(model => model.ImagePath, new { type = "file", multiple = "multiple", NAME = "files" }) 
     </div> 
     <div class="editor-label"> 
      @*Future Upload links*@ 
      @*@Html.LabelFor(model => model.Images) 
      @Html.TextBoxFor(model => model.Images, new { type = "file", multiple = "multiple" }) 
      @Html.ValidationMessageFor(model => model.Images)*@ 
     </div> 

     <p><input type="submit" value="Create" /></p> 
    </fieldset> 
} 
<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

dépôt

public void Save(PostModel Post) 
{ 
    try 
    { 
     if (Post.PostID == 0) 
     { 
      context.Posts.Add(Post); 
     } 
     else 
     { 
      PostModel dbEntry = context.Posts.Find(Post.PostID); 
      if (dbEntry != null) 
      { 
       dbEntry.Heading = Post.Heading; 
       dbEntry.PostBody = Post.PostBody; 

      } 
     } 
     context.SaveChanges(); 

    } 
    catch (DbEntityValidationException ex) 
    { 
     // Retrieve the error messages as a list of strings. 
     var errorMessages = ex.EntityValidationErrors 
       .SelectMany(x => x.ValidationErrors) 
       .Select(x => x.ErrorMessage); 

     // Join the list to a single string. 
     var fullErrorMessage = string.Join("; ", errorMessages); 

     // Combine the original exception message with the new one. 
     var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); 

     // Throw a new DbEntityValidationException with the improved exception message. 
     throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); 
    } 
} 

Modèle

public partial class PostModel 
    { 
     [Key] 
     [HiddenInput(DisplayValue = false)] 
     public int PostID { get; set; } 
     [Required(ErrorMessage = "Heading is Required")] 
     [Display(Name = "Heading")] 
     public string Heading { get; set; } 
     [Required(ErrorMessage = "Body is Required")] 
     [DataType(DataType.MultilineText)] 
     [Display(Name = "Body")] 
     public string PostBody { get; set; } 
     public string ImageDisplayName { get; set; } 
     public string ImagePath { get; set; } //Temporarly here until I can get the ImageModel Method Working 
     //public virtual ICollection<ImageModel> Images { get; set; } 
    } 

Contrôleur

public ViewResult Create() 
    { 
     return View("Edit", new PostModel()); 

    } 

public ViewResult Edit(int PostID) 
{ 
    PostModel editedItem = repository.Posts 
    .FirstOrDefault(p => p.PostID == PostID); 
    return View(editedItem); 
} 
[HttpPost] 
public ActionResult Edit(PostModel Post, IEnumerable<HttpPostedFileBase> files) 
{ 
    if (ModelState.IsValid) 
    { 
     foreach (var file in files) 
     { 
      PostModel post = new PostModel(); 
      if (file != null && file.ContentLength > 0) 
      { 
       string displayName = file.FileName; 
       string fileExtension = Path.GetExtension(displayName); 
       string fileName = string.Format("{0}.{1}", Guid.NewGuid(), fileExtension); 
       string path = Path.Combine(Server.MapPath("~/Img/"), fileName); 
       file.SaveAs(path); 
       post.ImageDisplayName = displayName; 
       post.ImagePath = fileName; 
       post.PostBody = Post.PostBody; 
       post.Heading = Post.Heading; 
      } 
      repository.Save(post); 

     } 
    } 
    return RedirectToAction("display"); 
} 

Répondre