大家好,所以我尝试使用asp.net mvc创建一个应用程序,该代码第一个数据库允许用户能够创建一个包含他们希望的图像数量的博客文章。只要我的头部,身体和图像区域已满或者我从头部和身体上进行验证,该应用程序就可以完美运行。问题是如果我对头部和身体进行验证,程序会因此验证错误而崩溃:< / p>
DbEntityValidationException 类型&#39; System.Data.Entity.Validation.DbEntityValidationException&#39;的例外情况发生在Crud.dll中但未在用户代码中处理
其他信息:一个或多个实体的验证失败。请参阅&#39; EntityValidationErrors&#39;物业详情。验证错误是:标题是必需的;身体是必需的
感谢您对此问题的帮助。
查看
@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");
}
答案 0 :(得分:0)
如果实际上不需要字段,为什么要添加[必需]属性?请参阅此处了解字符串处理必需属性的方法 - Allow empty strings for fields marked with PhoneAttribute or UrlAttribute