在我的配方中,我想创建一些验证逻辑,为此我使用了IValidateObject接口。在运行之后,我仍然收到黄色错误消息,并且在调试时,我注意到Validat函数甚至还没有被调用。
我希望有人能解释一下我怎样才能让验证正常工作。
public class RecipeLine : IValidatableObject
{
[Display(Name = "Receptregel")]
public string QuantityUomIngredient => $"{Quantity} {UnitOfMeasure?.Abbreviation ?? ""} {Ingredient?.Name ?? ""}";
private RecipeApplicationDb db = new RecipeApplicationDb();
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
// Split the incoming string
string[] valueAsString = QuantityUomIngredient.Split();
if (QuantityUomIngredient != null)
{
// Check if the string has the proper length
if (valueAsString.Length < 3)
{
var StringErrorMessage = "Er zijn onvoldoende gegevens ingevuld. voorbeeld: 1,2 kg Aardappelen";
yield return new ValidationResult(StringErrorMessage);
}
// Check if the first value of the string is a double
double quantityValue;
bool quantity = double.TryParse(valueAsString[0], out quantityValue);
if (!quantity)
{
var QuantErrorMessage = "De hoeveelheid moet een numerieke waarde zijn.";
yield return new ValidationResult(QuantErrorMessage);
}
// Check if the UOM value exists in the database
string uom = valueAsString[1];
bool checkUOM = (from x in db.UnitOfMeasures where x.Abbreviation.ToLower() == uom select x).Count() > 0;
if (!checkUOM)
{
var UomErrorMessage = "Er is geen juiste maateenheid ingevoerd.";
yield return new ValidationResult(UomErrorMessage);
}
// Check if the ingredient exists in the database
string ingredient = valueAsString[2];
bool checkIngredient = (from x in db.Ingredients where x.Name.ToLower() == ingredient.ToLower() select x).Count() > 0;
if (!checkIngredient)
{
var IngredientErrorMessage = "Er is geen juist ingredient ingevoerd.";
yield return new ValidationResult(IngredientErrorMessage);
}
}
}
}提前谢谢。
==================EDIT======================
也许这也很重要。在控制器中,我放置了一个自定义模型绑定器。在调试时,我注意到我无法访问验证函数,但它直接转到db.savechanges。
// POST: RecipeLine/Create
[HttpPost]
public ActionResult Create([ModelBinder(typeof(RecipeLineCustomBinder))] RecipeLine recipeLine)
{
ViewBag.ingredients = (from x in db.Ingredients select x).ToList();
ViewBag.uom = (from x in db.UnitOfMeasures select x).ToList();
if (ModelState.IsValid)
{
db.RecipeLines.Add(recipeLine);
db.SaveChanges();
return RedirectToAction("Create", new { id = recipeLine.RecipeId });
}
return View(recipeLine);
}发布于 2015-10-15 16:24:08
仅当属性验证成功时才使用IValidatableObject。
https://stackoverflow.com/questions/33142597
复制相似问题