Hi everyone so I am trying to create an application using asp.net mvc with a code first database that allows the users to be able to create a blog post with as many images as they wish. The application works perfect as long as I have the head,body and image fields full or if I take validation off the head and body.The issue is if I have validation on the head and the body the program crashs with this validation error:
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
Thanks for your help with this issue.
View
@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>
Repository
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);
}
}
Model
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; }
}
Controller
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");
}