I'm New To MVC and Trying to build the code but get's error as "
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
"
My Model is:-
namespace RsbEngMvc.Models
{
[Table("TblWhyUs")]
public class WhyUs
{
public int ID { get; set; }
[Required(ErrorMessage="Please Enter Heading")]
[StringLength(100, ErrorMessage = "Heading cannot be longer than 100 characters.")]
public string Heading { get; set; }
[Display(Name = "Body Text")]
[Required(ErrorMessage = "Please Enter Body Text")]
[StringLength(2000, ErrorMessage = "Body Text cannot be longer than 2000 characters.")]
public string Body { get; set; }
[Display (Name="Image")]
[StringLength(150, ErrorMessage = "Image Name cannot be longer than 150 characters.")]
public string Img { get; set; }
}
}
and Controller Is:-
[HttpPost]
[ActionName("AdminWhyUsCreate")]
public ActionResult AdminWhyUsCreate_Post(FormCollection formCollection,HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
WhyUs whyuss = new WhyUs();
if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName);
whyuss.Img = file.FileName;
}
whyuss.Heading = formCollection["Heading"];
whyuss.Body = formCollection["Body"];
RsbEnggContext DbContext = new RsbEnggContext();
DbContext.whyus.Add(whyuss);
DbContext.SaveChanges();
return RedirectToAction("AdminWhyUs");
}
return View();
}
What I have tried:
I tried Jquery validation in my View Also but it's not working :-
@using (Html.BeginForm("AdminWhyUsCreate", "MyAdmin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
Create New Entry in WhyUs
@Html.LabelFor(model => model.Heading)
@Html.TextBoxFor(model => model.Heading, new { @class = "form-control",maxlength="100" })
@Html.ValidationMessageFor(model => model.Heading)
@Html.LabelFor(model => model.Body)
@Html.TextAreaFor(model => model.Body, new { @class = "form-control", @rows = 5,maxlength="3000" })
@Html.ValidationMessageFor(model => model.Body)
@Html.LabelFor(model => model.Img)
@*@Html.EditorFor(model => model.Img)*@
@*@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { cssclass = "btn btn-info", enctype = "multipart/form-data" }))*@
@* { *@
<input type="file" id="FileUpload" name="file" />
@* @Html.ValidationMessageFor(model => model.Img)*@
@* } *@
<input type="submit" value="Create" class="btn btn-dark" />
}
@Html.ActionLink("Back to List", "AdminWhyUs")
<script type="text/javascript">
$(document).ready(function () {
$('#Create').click(function () {
if ($('#Heading').val == "") {
alert('Heading Cannot Be Blank for Record');
return false;
}
else if ($('#Body').val == "") {
alert('Body Index Cannot Be Blank for Record');
return false;
}
return true;
});
});
It Gives the error :-
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
On This Line:-
DbContext.SaveChanges();