Validation failed for one or more entities. - asp.net-mvc

When I try to Update IsApproved=true to approve the property, I am getting the following error.
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. The validation errors are: Please upload the image.; Please select some property features.
Please help me out. Thanx in advance.
My Model is as follows:
[Table("AddProperty")]
public class AddProperty
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
public List<TransactionType> TransactionType_List { get; set; }//Used to populate dropdown list values
[Required(ErrorMessage = "Please select the category.")]
[Display(Name = "Category:")]
public int TransactionTypeId { get; set; }//Used to post back selected value
public virtual TransactionType TransactionType { get; set; }
public List<PropertyType> PropertyType_List { get; set; }//Used to populate dropdown list values
[Required(ErrorMessage = "Please select the property.")]
[Range(1, int.MaxValue, ErrorMessage = "Please select the property.")]
[Display(Name = "Property:")]
public int PropertyTypeId { get; set; }//Used to post back selected value
public virtual PropertyType PropertyType { get; set; }
public List<PropertyList> PropertyList_List { get; set; }//Used to populate dropdown list values
[Required(ErrorMessage = "Please select the property type.")]
[Range(1, int.MaxValue, ErrorMessage = "Please select the property type.")]
[Display(Name = "Property Type:")]
public int PropertyListId { get; set; }//Used to post back selected value
public virtual PropertyList PropertyList { get; set; }
[Required(ErrorMessage = "Property Name is required.")]
[StringLength(50, MinimumLength = 3, ErrorMessage = "Building Name length should be between 3 and 50.")]
[Display(Name = "Property Name:")]
public string PropertyName { get; set; }
public List<FlatDescription> FlatDescription_List { get; set; }//Used to populate dropdown list values
[Required(ErrorMessage = "Description is required.")]
[Display(Name = "Description:")]
public int FlatDescriptionId { get; set; }
public virtual FlatDescription FlatDescription { get; set; }
public List<Bathroom> Bathrooms_List { get; set; }//Used to populate dropdown list values
[Required(ErrorMessage = "No of Bathrooms is required.")]
[Display(Name = "No of Bathrooms:")]
public int BathroomId { get; set; }//Used to post back selected value
public virtual Bathroom Bathroom { get; set; }
public List<City> City_List { get; set; }//Used to populate dropdown list values
[Required(ErrorMessage = "Please select the city.")]
[Display(Name = "City:")]
public int CityId { get; set; }//Used to post back selected value
public virtual City City { get; set; }
[Required(ErrorMessage = "Location is required.")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Location length should be between 3 and 30.")]
[Display(Name = "Location:")]
public string Location { get; set; }
[Required(ErrorMessage = "Property Price is required.")]
[Range(typeof(decimal),"1","10000000",ErrorMessage = "Please enter valid property price.")]
[RegularExpression(#"^\d+.\d{0,2}$", ErrorMessage = "Only 2 decimal point values are allowed.")]
[Display(Name = "Enter Property Price:")]
public decimal PropertyPrice { get; set; }
//[Required(ErrorMessage = "Please upload the image.")]
[Display(Name = "Upload Image:")]
[NotMapped]
[ValidatePhoto]
public HttpPostedFileBase PropertyPhoto { get; set; }
public string ImageURL { get; set; }
public List<Facilities> Facilities_List { get; set; }//Used to populate dropdown list values
[Required(ErrorMessage = "Please select some property features.")]
[Display(Name = "Select Property Features:")]
[NotMapped]
public int[] SelectedIds { get; set; }//Used to post back selected value
public string PropertyFeatures { get; set; }
[HiddenInput(DisplayValue = false)]
public DateTime CreateDate { get; set; }
[HiddenInput(DisplayValue = false)]
public DateTime? UpdateDate { get; set; }
[HiddenInput(DisplayValue = false)]
public int CreateUser { get; set; }
[HiddenInput(DisplayValue=false)]
public int? UpdateUser { get; set; }
[HiddenInput(DisplayValue = false)]
public bool IsApproved { get; set; }
[HiddenInput(DisplayValue = false)]
public bool IsActive { get; set; }
}

Use this to track the error:
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}

Related

ASP.NET MVC5. Error code not allowing controller to be view in browser

HAVING TROUBLE GETTING MY EVENTS CONTROLLER TO SHOW IN BROWSER. I AM RECEIVING ERROR MESSAGE THAT MY COLUMN NAME IS INVALID
SqlException: Invalid column name 'City'.
Invalid column name 'State'.
EVENT MODEL code
public class Events
{
[Key]
public int EventsId { get; set; }
[Required(ErrorMessage = "Title is requied")]
[StringLength(50, ErrorMessage = "Title cannot be more than 50 characters")]
public string EventTitle { get; set; }
[StringLength(150, ErrorMessage = "Description should not exceed 150 characters")]
public string EventDescription { get; set; }
[Required]
public DateTime EventStartTime { get; set; }
[Required(ErrorMessage = "Start Date cannot be in the past")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0;MMdd/yyyy}")]
public DateTime EventStartDate { get; set; }
[Required]
public DateTime EventEndTime { get; set; }
[Required(ErrorMessage = "End date cannot be less than Start date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0;MMdd/yyyy}")]
public DateTime EventEndDate { get; set; }
public string City { get; set; }
public string State { get; set; }
public string EventType { get; set; }
[Required]
public string OrganizerName { get; set; }
public string OrganizerContactInfo { get; set; }
[Required(ErrorMessage = " Max tickets cannot be 0")]
public int MaxTickets { get; set; }
[Required(ErrorMessage = "Avaliable tickets cannot be 0")]
public int AvaliableTickets { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
throw new NotImplementedException();
}
}
}
here
enter image description here
There is a lot of information missing. My guess would be the Events table in your database does not contain City or State columns.

A specified Include path is not valid on eager loading

I am using eager loading in entity framework. My Model class is like
public class EmployeeMaster : AbsCommonParameters
{
[Key]
public int Id { get; set; }
public string EmpId { get; set; }
[Required(ErrorMessage = "Employee name is required")]
public string Name { get; set; }
[Required(ErrorMessage = "Employee geography is required")]
public string Geography { get; set; }
public string EmailId { get; set; }
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[Column(TypeName = "Date")]
[Display(Name = "Date Of Joining")]
public Nullable<DateTime> DOJ { get; set; }
[Required(ErrorMessage = "Employee designation is required")]
public string Designation { get; set; }
[NotMapped]
public List<CenterMaster> lstCenters { get; set; }
[NotMapped]
public List<CostCodeMaster> lstCostCode { get; set; }
}
In Controller Index Action my Code is like this
public ActionResult Index()
{
var lstUser = db.ObjEmployeeMaster.Include(p => p.lstCenters).
Include(p => p.lstCostCode).Where(x => x.DeletedStatus == false).ToList();
return View(lstUser);
}
Also In DBContext Constructor I have used
this.Configuration.LazyLoadingEnabled = false;
After this I got error
A specified Include path is not valid
Please help where I am wrong.
Thanks in advance.

DropDownListFor selection not being saved

I am new to MVC. I am using a DropDownListFor to display a list of company names and, based on the selection made, filling in other Customer fields. The customer fields are being populated fine, but when I attempt to POST the record, I get a validation error "Company name is required", even though the company name has been selected in the DropDownListFor. Here is the ViewModel:
namespace CMSUsersAndRoles.Models
{
public class QuoteViewModel
{ [Key]
[Display(Name = "Quote Id")]
public int QuoteId { get; set; }
// Columns from Customer table
[Required(ErrorMessage = "Please select a company")]
[Display(Name = "Customer Id")]
public int? CustomerId { get; set; }
[Display(Name = "Sales Rep")]
public string SalesRep { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
public string Company { get; set; }
[Display(Name = "Address 1")]
public string Address1 { get; set; }
[Display(Name = "Address 2")]
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
[StringLength(10)]
[Display(Name = "Zip Code")]
[RegularExpression(#"^\d{5}(-\d{4})?$", ErrorMessage = "Invalid Zip Code")]
public string PostalCode { get; set; }
[Phone]
[Display(Name = "Work Phone")]
public string WorkPhone { get; set; }
[Phone]
[Display(Name = "Cell Phone")]
public string CellPhone { get; set; }
[EmailAddress]
public string Email { get; set; }
[Range(0, 100)]
public decimal? Discount { get; set; }
[Display(Name = "Payment Terms")]
public int? PaymentTerms { get; set; }
// Columns from QuoteDetail table
[Display(Name = "Quote Detail")]
public List<QuoteDetail> QuoteDetail { get; set; }
// Columns from Quote table
public decimal Subtotal { get; set; }
public decimal Tax { get; set; }
public decimal Total { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Quote Date")]
public DateTime? QuoteDate { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Good Until")]
public DateTime? GoodUntil { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Quote Sent")]
public DateTime? QuoteSent { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date Approved")]
public DateTime? DateApproved { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date Ordered")]
public DateTime? DateOrdered { get; set; }
}
}
Here is the code from the View:
#Html.DropDownListFor(model => model.CustomerId, new SelectList(ViewBag.Customers, "CustomerId", "Company"), "---Select one---", new { htmlAttributes = new { #class = "company" } });
#Html.HiddenFor(model => model.Company)
#Html.ValidationMessageFor(model => model.Company, "", new { #class = "text-danger" })
Here is the Get:
public ActionResult Create()
{
QuoteViewModel qvm = new QuoteViewModel();
var customers = db.Customers.ToList();
ViewBag.Customers = customers;
return View(qvm);
}
And here is the code for the POST:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(QuoteViewModel qvm)
{
if (ModelState.IsValid)
{
Quote quote1 = new Quote();
quote1.CustomerId = qvm.CustomerId;
...
customer.CustomerId = (int)qvm.CustomerId;
...
customer.Company = qvm.Company;
db.Entry(customer).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
var objContext = ((IObjectContextAdapter)db).ObjectContext;
// Get failed entry
var entry = ex.Entries.Single();
// Now call refresh on ObjectContext
objContext.Refresh(RefreshMode.ClientWins, entry.Entity);
}
return RedirectToAction("Index");
}
var customers = db.Customers.ToList();
ViewBag.Customers = customers;
return View(qvm);
}
What am I missing? Any help will be much appreciated.
I was not setting the value of the HiddenFor below. Thanks, #StephenMuecke.
#Html.HiddenFor(model => model.Company)

Save data finally after all action completed

hi please help me I have 5 model and I want to save all model at once so please help me
my models are
public partial class EmployeeMainTable
{
public EmployeeMainTable()
{
this.employee_DepartmentTable = new List<EmployeeDepartmentTable>();
}
public int EmployeeId { get; set; }
[Required(ErrorMessage = "Enter the Name")]
public string EmployeeName { get; set; }
[Required(ErrorMessage = "Enter date of joining")]
[DataType(DataType.Date)]
public System.DateTime EmployeeDateOfJoining { get; set; }
[Required(ErrorMessage = "Department Required")]
public int EmployeeDepartmentId { get; set; }
[Required(ErrorMessage = "Designation Required")]
public int EmployeeDesignationId { get; set; }
[Required(ErrorMessage = "Location Required")]
public int EmployeeLocationId { get; set; }
[Required(ErrorMessage = "Employee status Required")]
public int EmployeeStatusId { get; set; }
[Required(ErrorMessage = "Employee Type Required")]
public int EmployeeTypeId { get; set; }
[Required]
public bool EmployeeIsActive { get; set; }
[Required(ErrorMessage = "Confirmed Date Required")]
[DataType(DataType.Date)]
public DateTime EmployeeConfirmDate { get; set; }
[Required(ErrorMessage = " Email required")]
[RegularExpression(#"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = " Must be a valid e-mail address ")]
public string EmployeeEmailId { get; set; }
[Required(ErrorMessage = "Contact Number Required")]
public string EmployeeContactNumber { get; set; }
[Required(ErrorMessage = "Date of Birth Required")]
[DataType(DataType.Date)]
public DateTime EmployeeDateOfBirth { get; set; }
public ICollection<EmployeeAssetsTable> employee_AssetsTable { get; set; }
public List<EmployeeDepartmentTable> employee_DepartmentTable { get; set; }
public ICollection<EmployeeDesignationTable> employee_DesignationTable { get; set; }
public ICollection<EmployeeEducationDetailTable> employee_EducationTable { get; set; }
public ICollection<EmployeeFamilyTable> employee_FamilyTable { get; set; }
public ICollection<EmployeeLocationTable> employee_LocationTable { get; set; }
public ICollection<EmployeeStatusTable> employee_StatusTable { get; set; }
public ICollection<EmployeeTypeTable> employee_TypeTable { get; set; }
public virtual ICollection<EmployeePreviousCompanyDetailTable> employee_PreviousCompanyDetailTable { get; set; }
public virtual ICollection<EmployeeDocumentsTable> employee_DocumentTable { get; set; }
likewise I have 5 models
what I need I need to pas model from action to action and if I click submit button in last section data get saved from all model at once
If I understand correctly, can't you just have a property in model #2 for model#1, a property for model #2 and #1 in model #3, and so forth..
Or use custom ViewModels that's served to fit your purpose.
I just started with MVC so this is my novice advice, don't take it for granted.

Pass model to controller and send result to page not using form submit

I have a page I am writing to send emails to customers. One of the ways to select customers to email is to select products they have. Each product has different detail information and you will also be able to choose specifics about the product to narrow down who you are emailing.
Because this is going to be complex I need to do the processing to come up with the customer email list on the controller side but it would be a nightmare to try to pull all the data form the controls to send to it manually.
I would like to use an AJAX call that on the controller side would get the model tied to the view, query the database, and send back the list of emails so on the view I can pop up outlook for them with the list of email addresses already populated. Because I need to go back to the view with data I don't think I can do this with a form post which is how I normally get model into into the controller.
Does someone know how I could accomplish this?
Here are some of the clases I have to try to help people understand my layout
public class ProductType
{
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[Required(ErrorMessage = "Please enter a product type description")]
public string Description { get; set; }
public virtual ICollection<ProductTypeDetail> ProductDetails { get; set; }
}
public class ProductTypeDetail
{
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[HiddenInput(DisplayValue = false)]
public int? ProductTypeID { get; set; }
public ProductType ProductType { get; set; }
[Required(ErrorMessage = "Please enter a description")]
public string Description { get; set; }
[Required(ErrorMessage = "Please enter a valid type")]
public string Type { get; set; }
public virtual ICollection<ProductTypeDetailValidValue> ValidValues { get; set; }
}
The above 2 classes are for product types which someone could enter anything for and as many as they want. The product details are detail information you might need to know about your products. For example you could have a product type of Vehicle Registration System and put a product detail item in that for a specific import process that pertains to the product they you need to know if they use or not.
public Customer()
{
SiteVisits = new List<SiteVisit>();
Payments = new List<Payment>();
Contacts = new List<CustomerEmail>();
}
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[Display(Name = "Name")]
[Required(ErrorMessage = "Please enter a customer name")]
public string CustomerName { get; set; }
[Display(Name = "Line 1")]
public string Address1 { get; set; }
[Display(Name = "Line 2")]
public string Address2 { get; set; }
[Display(Name = "Line 3")]
public string Address3 { get; set; }
[Display(Name = "Line 4")]
public string Address4 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
[HiddenInput(DisplayValue = false)]
[Required(ErrorMessage = "Please enter a customer type")]
public int CustomerTypeID { get; set; }
[Display(Name = "Type")]
public virtual CustomerType CustomerType { get; set; }
[HiddenInput(DisplayValue = false)]
[Required(ErrorMessage = "Please enter a customer status")]
public int CustomerStatusID { get; set; }
[Display(Name = "Status")]
public virtual CustomerStatus CustomerStatus { get; set; }
[DataType(DataType.MultilineText)]
public string Comments { get; set; }
[Required(ErrorMessage = "Please enter an expiration year")]
public long ExpirationYear { get; set; }
[Required(ErrorMessage = "Please enter an expiration month")]
public long ExpirationMonth { get; set; }
[Required(ErrorMessage = "Please enter a control name")]
public string ControlName { get; set; }
public Boolean Networked { get; set; }
public long Population { get; set; }
[Display(Name = "First Fiscal Month")]
public long FirstMonth { get; set; }
[Display(Name = "FTP User Name")]
public string FTPUserName { get; set; }
[Display(Name = "FTP Password")]
public string FTPPassword { get; set; }
[Display(Name = "Customer ID")]
public string CustomerUpdateID { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Customer Since")]
public DateTime? StartDate { get; set; }
public virtual ICollection<CustomerPhoneNumber> PhoneNumbers { get; set; }
public virtual ICollection<CustomerProduct> Products { get; set; }
public virtual ICollection<CustomerEmail> Contacts { get; set; }
public virtual ICollection<SiteVisit> SiteVisits { get; set; }
public virtual ICollection<Payment> Payments { get; set; }
}
public class CustomerProduct
{
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[HiddenInput(DisplayValue = false)]
public int? ProductTypeID { get; set; }
public virtual ProductType ProductType { get; set; }
[HiddenInput(DisplayValue = false)]
public int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
[HiddenInput(DisplayValue = false)]
public int? VersionID { get; set; }
public virtual ProductVersion Version { get; set; }
[HiddenInput(DisplayValue = false)]
public int? StatusID { get; set; }
public virtual ProductStatus Status { get; set; }
public virtual ICollection<CustomerProductDetail> ProductDetails { get; set; }
}
public class CustomerProductDetail
{
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[HiddenInput(DisplayValue = false)]
public int CustomerProductID { get; set; }
public virtual CustomerProduct CustomerProduct { get; set; }
[HiddenInput(DisplayValue = false)]
public int ProductTypeDetailID { get; set; }
public virtual ProductTypeDetail ProductTypeDetail { get; set; }
//[Required(ErrorMessage = "Please enter a value")]
public string Value { get; set; }
}
So above I have the customer class. Each customer can be set up with any number of the product types you have set up and you can select values for the product details of that product type for this particular customer. The customers also contain contacts. that is the class that has the email addresses.
So I need to show a screen that displays all the product types you have set up and lets you select values for detail items on products you select then I need to query and find customers that match this
All I needed to do was serialize the form and pass it as data in my ajax call. If on the Controller side that is getting called I have an argument that is of the same type as the model my view is strongly typed to the model binder is smart enough to fill in my object automatically

Resources