【发布时间】:2017-01-29 21:06:30
【问题描述】:
大家好,我正在尝试使用带有代码优先数据库的 asp.net mvc 创建一个应用程序,该数据库允许用户创建包含任意数量图像的博客文章。只要我的头部、身体和图像字段已满,或者如果我对头部和身体进行验证,该应用程序就可以完美运行。问题是如果我在头部和身体上进行验证,程序会因以下验证错误而崩溃:
DbEntityValidationException Crud.dll 中出现“System.Data.Entity.Validation.DbEntityValidationException”类型的异常,但未在用户代码中处理
附加信息:一个或多个实体的验证失败。有关更多详细信息,请参阅“EntityValidationErrors”属性。验证错误是:标题是必需的;正文是必需的
感谢您对此问题的帮助。
查看
@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>
存储库
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);
}
}
型号
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; }
}
控制器
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");
}
【问题讨论】:
标签: c# asp.net-mvc validation ef-code-first code-first