I have a product database, where people can add specifications to a product. Currently this looks like this: Application Screenshot
All these different specifications need custom validation so users can only enter certain value's for certain specifications. Currently it's defined in the database which specification is which datatype. Every specification has a foreign key to a datatype. I think i need to check which attribute is currently selected when submitting the form and have some sort of dynamic validation for the value field. But i can't find any similair situations already posted here.
I posted my current code, which is more of an outline of how i think it should work.
ValidationAttribute:
public class DropdownBasedValueValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
AddSpecificationViewModel viewModelUsed = (AddSpecificationViewModel)validationContext.ObjectInstance;
switch(viewModelUsed.datatypeSelected)
{
case "Int32":
return checkInt32((int)value);
case "Boolean":
return checkBool((bool)value);
case "String":
return checkString(value.ToString());
}
return new ValidationResult("Entered value is incorrect");
}
}
ViewModel:
[Display(Name = "Value")]
[Required]
[DropdownBasedValueValidation()]
public string Value { get; set; }
View:
@using (Html.BeginForm("AddSpecification", "Products", FormMethod.Post))
{
@Html.HiddenFor(m => m.productIdCode)
<div class="col-md-4">
<div class="form-group">
@Html.LabelFor(model => model.labelDropwdownValue)
@Html.DropDownList("LabelId", null, "All", new { @class = "form-control" })
</div>
</div>
<div class="col-md-8">
<div class="form-group">
@Html.ValidationMessageFor(m => m.Value)
@Html.LabelFor(m => m.Value)
@Html.TextBoxFor(m => m.Value, null, new { @class = "form-control" })
</div>
</div>
<div class="col-md-2">
<button type="submit" class="btn btn-primary btn-block">Add Specification</button>
</div>
}
I'm pretty new to MVC so i hope you guys can help me out here :)