ASP.NET 用于查询数据库以获取唯一字段值的代码片段

ASP.NET code snippit to query database for unique field value

我正在尝试创建自定义远程数据注释来检查唯一值。

到目前为止我有:

[Remote("checkForUniqueSpeciesName", "Create", ErrorMessage = "A Species by that name already exists.")]
public string SpeciesName { get; set; }

public ActionResult checkForUniqueSpeciesName(string species_name)
    {
        bool is_unique = ........
        return Json(is_unique, JsonRequestBehavior.AllowGet);
    }

老实说,我不太明白它是如何工作的,我只是想按照网上找到的例子去做。我猜想 checkForUniqueSpeciesName 是在提交表单时调用的,方法 returns 是对还是错。是否需要在视图中添加一些内容才能显示验证消息,例如?

@Html.ValidationMessageFor(model => model.SpeciesName, "", new { @class = "text-danger" })

我需要那个吗?

型号Species.cs: public class 物种 { [钥匙] public int SpeciesId { 得到;放; }

    [Display(Name = "Species")]
    [Required(ErrorMessage = "You must enter a species name.")]
    [Remote("CheckForUniqueSpeciesName", "Create", ErrorMessage = "A Species by that name already exists.")]
    public string SpeciesName { get; set; }
}

控制器SpeciesController.cs:

命名空间Gators3.Controllers { public class 物种控制器:控制器 { private GatorsContext db = new GatorsContext();

    // GET: Species
    public ActionResult Index()
    {
        return View(db.Species.ToList());
    }

    // GET: Species/Create
    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "SpeciesId,SpeciesName")] Species species)
    {
        if (ModelState.IsValid)
        {
            db.Species.Add(species);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(species);
    }

    public ActionResult CheckForUniqueSpeciesName(string speciesName)
    {
        using (GatorsContext ctx = new GatorsContext())
        {
            bool isUnique = !ctx.Species.Any(s => s.SpeciesName == speciesName);
            return Json(isUnique, JsonRequestBehavior.AllowGet);
        }
    }
.
.
.
.

View Views->Species->Create.cshtml:

@model Gators3.Models.Species

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Species</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.SpeciesName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.SpeciesName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.SpeciesName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

I guess checkForUniqueSpeciesName is called when the form is submitted, and the method returns true or false.

不,事实并非如此。 [RemoteAttribute] 会自动将一些 JavaScript 添加到您的页面,这将在您的控制器上调用一个方法来执行一些服务器端验证并在页面上显示结果,而无需用户提交整个 HTML 形式。即当您跳出文本框时调用验证,而不是当您单击提交时。

根据您的代码,我假设您的控制器名为 CreateController?

我猜你只是缺少数据访问代码来实际检查唯一性?

所以需要这样的东西:

public ActionResult CheckForUniqueSpeciesName(string speciesName)
{
    using (YourEntityFrameworkDbContext ctx = new YourEntityFrameworkDbContext())
    {
        bool isUnique = !ctx.Species.Any(s => s.SpeciesName == speciesName);
        return Json(isUnique , JsonRequestBehavior.AllowGet);
    }
}

那么在你看来,你只需要这样的东西:

@Html.ValidationMessageFor(x => x.SpeciesName)

这将显示您在 [Remote] 属性中指定的验证消息。

顺便说一句,作为旁注 - 您应用于某些代码的编码 conventions/casing 不会受到大多数 C# 程序员的欢迎(除非您的团队遵守不寻常的标准) 所以请注意我应用的格式。

更新 - 我认为您的代码需要具有以下内容:

[Remote("CheckForUniqueSpeciesName", "Species", ErrorMessage="A Species by that name already exists.")]