【问题标题】:ASP.NET code snippit to query database for unique field value用于查询数据库以获取唯一字段值的 ASP.NET 代码段
【发布时间】:2015-06-08 22:12:48
【问题描述】:

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

到目前为止我有:

[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是在提交表单时调用的,该方法返回true或false。是否需要在视图中添加一些内容以使验证消息出现,例如?

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

我需要那个吗?

Model Species.cs: 公共类物种 { [钥匙] 公共 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; }
}

Controller SpeciesController.cs:

命名空间 Gators3.Controllers { 公共类 SpeciesController : 控制器 { 私有 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);
        }
    }
.
.
.
.

查看视图->物种->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")
}

【问题讨论】:

  • 我认为你最好不要再跟着你不理解的例子,而是学会理解它们。
  • 是的,您需要 @Html.ValidationMessageFor() 才能显示消息(但它必须是 m =&gt; m.species_name - 即匹配属性名称和控制器参数名称 - 或者如果属性是 SpeciesId,那么方法参数需要是SpeciesId)。并且在提交表单时不会调用您的方法 - 它是预先调用的,如果该方法返回 false,则在更正错误之前不会提交表单
  • @StephenMuecke -- 是的,我的意思是SpeciesName,我做了剪切和粘贴。感谢您清除验证运行的时间。关于在“...”中添加什么有什么想法吗?
  • 没有看到更多代码,无法判断,但可能类似于bool is_unique = !db.Species.Any(s =&gt; s.SpeciesName == SpeciesName)

标签: asp.net asp.net-mvc custom-data-attribute


【解决方案1】:

我猜 checkForUniqueSpeciesName 在表单被调用时被调用 提交,方法返回真或假。

不,事实并非如此。 [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] 属性中指定的验证消息。

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

更新 - 我认为您的代码需要具备以下条件:

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

【讨论】:

  • 感谢您的帮助和解释!显然我才刚刚开始。控制器是SpeciesController,并有一个Create 方法。几乎是为我建造的脚手架。所以,我把你的代码放在控制器中(除了我必须将s=s.SpeciesName 更改为s=&gt;s.SpeciesName)保持你的编码约定(我应该学会遵守)。我确保Remote 注释中的方法名称匹配。发生的情况是,当我在创建页面中单击提交时,无论物种名称是否唯一,都没有任何反应。我将添加更多代码。
  • 远程验证应该在您离开物种文本框时进行,而不是在您提交表单时进行。我认为您的问题是您在 [Remote] 声明中的论点。我已经更新了我认为应该是的答案。
  • 做到了。我对使用控制器和控制器操作方法感到困惑。我看到的很多示例都是针对用户名或电子邮件的,它们具有检查唯一性的特殊方法。
猜你喜欢
  • 1970-01-01
  • 2015-11-20
  • 1970-01-01
  • 2017-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-04
  • 1970-01-01
相关资源
最近更新 更多