无法通过远程验证提交

问题描述

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

这是我的代码:

ProjectModel:

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

ProjectsController:

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

Project.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>

解决方法

对我来说最佳实践:

ProjectModel:

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

ProjectsController:

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

        return Json(true,JsonRequestBehavior.AllowGet);
    }
,

ProjectNameVerify控制器更改为此。 False,然后显示错误消息,true,则可以提交表单。

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

参考:Remote Validation In MVC 5 Using Remote Attribute

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...