Here's the problem. I have a [Range] attribute above the SalesCenterId property of my ViewModel. On my view side I have dropdown list with a default option "---Select---" and some Sales Centers with different Id-s. For example, if I set the Range between 0 and 1, then when selecting a sales center with Id = 2, my custom error message works. But when i select the default option "---Select---" (id = 0 , range between 1 and 1000) then the default error message is displayed: "The value '---Select---' is not valid for SalesCenterId." Why is this? I've checked through debugging and saw that when choosing "---Select---" Id = 0.
I'm using MVC core 2.2
ViewModel:
public class OrderViewModel
{
[Required(ErrorMessage = "*The Last Name field is required.")]
public string LastName { get; set; }
[Required(ErrorMessage = "*The First Name field is required.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "*The Middle Name field is required.")]
public string MiddleName { get; set; }
[Required(ErrorMessage = "*The Pin field is required.")]
public string Pin { get; set; }
[Required(ErrorMessage = "*The Phone field is required.")]
public string Phone { get; set; }
[Required(ErrorMessage = "*The Email field is required.")]
public string Email { get; set; }
[Required(ErrorMessage = "*The Serial Number field is required.")]
public string SerialNumber { get; set; }
[Range(1, 1000, ErrorMessage="jgsjfdngi")]
public int SalesCenterId { get; set; }
[Range(1, 999, ErrorMessage = "jgsjfdngi")]
public int OrderTimeId { get; set; }
[JsonIgnore]
[IgnoreDataMember]
public SalesCenter SalesCenter { get; set; }
public List<CartItem> Cart { get; set; }
public OrderTime OrderTime { get; set; }
public decimal TotalPrice { get; set; }
}
Validation message span:
<p><span asp-validation-for="SalesCenterId" class="error"></span></p>
Select list:
<td>
<select id="SCID" asp-for="SalesCenterId" asp-items="#ViewBag.SalesCenterId" class="input" style="width:200px; height:30px; padding:1.5%">
<option>---#Localizer["Select"]---</option>
</select><br />
</td>
I expect the output to be "jgsjfdngi", but the actual output is "The value '---Select---' is not valid for SalesCenterId."
Have you used ModelState.IsValid in your controller??
Try this
if (ModelState.IsValid)
{
// your code
return View();
}
return View();
Related
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.
I have a simple member registration data model with a few required properties and some optional properties. The BillToAddress property is optional.
public class MemberRegistration
{
[Required(ErrorMessage = "First Name is required.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is required.")]
public string LastName { get; set; }
[Required(ErrorMessage = "Email Address is required.")]
public string EmailAddress { get; set; }
public string PhoneNumber { get; set; }
[Required(ErrorMessage = "Password is required.")]
[MinLength(7, ErrorMessage = "Password must be at least 7 characters.")]
public string Password { get; set; }
private Address m_BillToAddress;
public Address BillToAddress
{
get
{
if (m_BillToAddress == null)
{
m_BillToAddress = new Address();
}
return m_BillToAddress;
}
}
}
If the user enters an optional bill to address, I would like the street, city, country, and postal code to be required. So I defined the Address data model, marking those properties as required.
public class Address
{
[Required(ErrorMessage = "Street Line 1 is required.")]
public string Street1 { get; set; }
public string Street2 { get; set; }
public string Street3 { get; set; }
public string Street4 { get; set; }
public string Street5 { get; set; }
[Required(ErrorMessage = "City is required.")]
public string City { get; set; }
[Required(ErrorMessage = "State or Province is required.")]
public string StateOrProvince { get; set; }
[Required(ErrorMessage = "Country is required.")]
public string Country { get; set; }
[Required(ErrorMessage = "Postal Code is required.")]
public string PostalCode { get; set; }
}
But now the model validation fails when I don't supply a bill to address. How can I annotate my models so that the bill to address is optional, but if it is supplied, then it has to include street, city, country, and postal code?
The problem was in MemberRegistration class. Because the BillToAddress property getter always returned a new, empty Address model, BillToAddress was never null and always correctly triggered the Address class validation. I changed BillToAddress to a simple auto-implemented property:
public Address BillToAddress { get; set; }
Now if I post a MemberRegistion without a BillToAddress, it passes validation because BillToAddress is an optional property.
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.
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;
}
In the Checkout Controller I have the code
[HttpPost]
public ActionResult AddressAndPayment(FormCollection values)
{
var order = new Order();
TryValidateModel(order);
....
The model looks like this
[Bind(Exclude="OrderId")]
public partial class Order
{
[ScaffoldColumn(false)]
public int OrderId { get; set; }
[ScaffoldColumn(false)]
public string Username { get; set; }
[Required(ErrorMessage= "First Name is required")]
[DisplayName("First Name")]
[StringLength(160)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is required")]
[DisplayName("Last Name")]
[StringLength(160)]
public string LastName { get; set; }
[Required(ErrorMessage="Address is required")]
[StringLength(70)]
public string Address { get; set; }
[Required(ErrorMessage = "City is required")]
[StringLength(40)]
public string City { get; set; }
[Required(ErrorMessage = "State is required")]
[StringLength(40)]
public string State { get; set; }
[Required(ErrorMessage = "Postal Code is required")]
[DisplayName("Postal Code")]
[StringLength(10)]
public string PostalCode { get; set; }
[Required(ErrorMessage="Country is required")]
[StringLength(40)]
public string Country { get; set; }
[Required(ErrorMessage= "Phone is required")]
[StringLength(24)]
public string Phone { get; set; }
[Required(ErrorMessage="Email Address is required")]
[DisplayName("Email Address")]
[RegularExpression(#"[A-za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage="Email is not valid.")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[ScaffoldColumn(false)]
public decimal Total { get; set; }
[ScaffoldColumn(false)]
public DateTime OrderDate { get; set; }
public List<OrderDetail> OrderDetails { get; set; }
}
I can stop right before the TryValidateModel line and look at form values like
? Request.Form["FirstName"]
"Michael"
? values["FirstName"]
"Michael"
So why does TryValidateModel(order); return false and the order object does not get populated?
Update
To clarify my question I know false means it can not bind but I do not know why it can not bind. Or that it should through the TryValidateModel(or even the ValidateModel)
But what is interesting is that if I change my method signature to
public ActionResult AddressAndPayment(Order order)
order gets populated correctly. So if it is able to bind in the Method call why not TryValidateModel(or even the ValidateModel)?
I am using MVC 4
TryValidateModel returns false when validation of the Form Model against your Orders Model Fails, thus Binding fails.
I hate using
TryValidateModel(order);
and prefer
ValidateModel(order);
early on while developing my page, because binding is a delicate process. This way, if the model fails to bind, I get an exception and an indicative error msg.