【问题标题】:Can not submit with Remote Validation无法通过远程验证提交
【发布时间】:2020-12-03 21:27:26
【问题描述】:

我的远程验证正在工作,但是当我提交表单时,光标聚焦在有效字段上,并且没有错误消息。

这是我的代码:

项目模型:

    [Required]
    [Remote("ProjectNameVerify", "Projects")]
    public string Name { get; set; }

项目控制器:

    public ActionResult ProjectNameVerify(string name)
    {
       // ... 
        return Json("msg", JsonRequestBehavior.AllowGet);
    }

项目.cshtml:

@using (Html.BeginForm())
@Html.AntiForgeryToken()
<div class="form-horizontal">
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control", Autofocus = "false" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
        <br>
    </div>
    <br>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-success" />
        </div>
    </div>
</div>

【问题讨论】:

    标签: c# asp.net model-view-controller asp.net-mvc-5


    【解决方案1】:

    ProjectNameVerify 控制器更改为此。为假,则显示错误信息,为真则可以提交表单。

    public JsonResult ProjectNameVerify(string name)
    {
       // ... 
        return Json({true/false}, JsonRequestBehavior.AllowGet);
    }
    

    参考:Remote Validation In MVC 5 Using Remote Attribute

    【讨论】:

    • 不允许返回字符串吗?
    • @ChingWang 对于远程验证,您需要返回布尔值,以便验证可以确定是否已经可以提交。如果您要实现的是返回错误消息,则需要将错误消息放在 Remote 属性上,它有一个属性来设置错误消息。
    【解决方案2】:

    我的最佳实践:

    项目模型:

    [Required]
    [Remote("ProjectNameVerify", "Projects")]
    public string Name { get; set; }
    

    项目控制器:

        public JsonResult ProjectNameVerify(string name)
        {
            if (Verify() == false)
            {
                return Json("errormsg", JsonRequestBehavior.AllowGet);
            }
    
            return Json(true, JsonRequestBehavior.AllowGet);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-10
      • 2012-09-19
      • 2018-07-19
      • 2021-11-15
      • 1970-01-01
      相关资源
      最近更新 更多