简体   繁体   English

如何在ASP.NET MVC中验证关键约束

[英]How to validate key constraints in ASP.NET MVC

I use the built in model validation which works great for specifying required fields and such but on my model I have specified key constraints so the combination of two columns are unique. 我使用内置的模型验证,该模型非常适合用于指定必填字段,但是在我的模型上,我已经指定了关键约束,因此两列的组合是唯一的。

How should I validate for this so it doesn't throw exception if user tries to add duplicate? 我应该如何对此进行验证,以便在用户尝试添加重复项时不会引发异常?

Here is my model: 这是我的模型:

public class EmailFilter
{
    public int ID { get; set; }
    [Required]
    [StringLength(100)]
    [Index("IX_FilterAndEmail", 2, IsUnique = true)]
    public string Email { get; set; }
    //This is an enum 
    [Required]
    [Index("IX_FilterAndEmail", 1, IsUnique = true)]
    public EmailFilterType Filter { get; set; }
}

And my create controller method. 还有我的create controller方法。 I tried to add an error but I am not doing it right. 我尝试添加错误,但操作不正确。 It stops the exception happening but it just returns to the listview. 它阻止了异常的发生,但仅返回到列表视图。 I'm not sure what the right way to validate here is. 我不确定在这里验证的正确方法是什么。

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,Email,Filter")] EmailFilter emailFilter)
    {
        if (ModelState.IsValid)
        {
            if(db.EmailFilters.Any(x => x.Filter == emailFilter.Filter && x.Email == emailFilter.Email))
            {
                // This doesn't seem to do anything and returns to listview not create view
                // "EFValidationSummary" is the id of my validation summary razor control
                ModelState.AddModelError("EFValidationSummary", "This filter already exists");
                return View(emailFilter);
            }
            else
            {
                db.EmailFilters.Add(emailFilter);
                db.SaveChanges();
            }

            return RedirectToAction("Index");
        }

        return View(emailFilter);
    }

How do I properly trigger an error and send back to the create page with the validation error displayed? 如何正确触发错误并发送回显示验证错误的创建页面?

The first parameter of AddModelError() is the name of the property in your model. AddModelError()的第一个参数是模型中属性的名称。 In your case, the error message would be displayed in the placeholder generated by 您的情况下,错误消息将显示在由生成的占位符中

@Html.ValidationMessageFor(m => EFValidationSummary)

but your model does not contain a property named EFValidationSummary . 但您的模型不包含名为EFValidationSummary的属性。 In order to display validation messages in the placeholder generated by @Html.ValidationSummary() , you need to provide an empty string for the first parameter 为了在由@Html.ValidationSummary()生成的占位符中显示验证消息,您需要为第一个参数提供一个空字符串

 ModelState.AddModelError("", "This filter already exists");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM