I am trying to validate if my dropdownlist’s item already exists in the DB. It should set Model.IsValid to false, but it pass true all the time, looks like validator just doesn’t get called
DropDownList code:
</td>
</tr>
<tr>
<td> @Html.Label("VendorId ") </td>
<td> @Html.DropDownListFor(x => x.id, new SelectList(Model.validatingVendors, "VendorKey", "VerndorID", Model.id)) @Html.ValidationMessageFor(x=>x.validatingVendors.FirstOrDefault(s=>s.VendorKey == x.id).VerndorID)</td>
</tr>
My custom Validator Class
public class VendorAttribute : ValidationAttribute
{
DataManager manager = new DataManager();
public override bool IsValid(object value)
{
var stringValue = Convert.ToString(value, CultureInfo.CurrentCulture);
if (value == null)
{
return true;
}
if ((value is string) && string.IsNullOrEmpty((string)value))
{
return true;
}
var name = value.ToString().ToLower();
// fake a database lookup and bring back two widgets
return (manager.VendorAllreadyExcists(stringValue));
}
public override string FormatErrorMessage(string name)
{
return name;
}
}
My Model class
public class VelidationVendorViewModel
{
public int VendorKey { get; set; }
[Required]
[Vendor(ErrorMessage = "Vendor Allerede eksister")]
public string VerndorID { get; set; }
public int LatestSalesCWeek { get; set; }
public bool Active { get; set; }
}
My parentViewModel
public class ParentViewModel
{
public List<FactRefIdFileFormatIdViewModel> model { get; set; }
public RefrenceDataViewModel refModel { get; set; }
public List<MetaFileFormatsViewModel> metaModel { get; set; }
public int id { get; set; }
public VelidationVendorViewModel vendorId { get; set; }
public IEnumerable<VelidationVendorViewModel> validatingVendors { get; set; }
}
SOLUTION
Just got it solved
[Required]
[Vendor(ErrorMessage = "Vendor Allerede eksister")]
public string VerndorID { get; set; }
on my viewmodel is wrong since i haveto move my custom validation to my id inside of my ParentViewModel so it looks like this:
public List<FactRefIdFileFormatIdViewModel> model { get; set; }
public RefrenceDataViewModel refModel { get; set; }
public List<MetaFileFormatsViewModel> metaModel { get; set; }
[Required]
[Vendor(ErrorMessage = "Vendor Allerede eksister")]
public int id { get; set; }
public VelidationVendorViewModel vendorId { get; set; }
public IEnumerable<VelidationVendorViewModel> validatingVendors { get; set; }
And last but not least my validation have to call ID instead of vendorId of specific item in a list like this :
@Html.ValidationMessageFor(x=>x.Id)
Just got it solved
on my viewmodel is wrong since i haveto move my custom validation to my id inside of my ParentViewModel so it looks like this:
And last but not least my validation have to call ID instead of vendorId of specific item in a list like this :
@Html.ValidationMessageFor(x=>x.Id)