远程验证不会触发操作

时间:2016-04-21 08:05:16

标签: asp.net asp.net-mvc

使用[Remote]验证以下字段为:

[Required]
[Remote("cnicExist", "evaluation", AdditionalFields = "id", HttpMethod = "POST", ErrorMessage = "An evaluation of probationer with this cnic already exists. Please provide another cnic.")]
public string cnic { get; set; }

查看是:

<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.10.2.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-ui-1.11.4.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.id)
    <div class="form-group">
        @Html.Label("CNIC:", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.cnic, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.cnic, "")
        </div>
    </div>
}

控制器是:

[HttpPost]
    public JsonResult cnicExist(int id, string cnic)
    {
        return Json(IsUnique(id, cnic));
    }
    private bool IsUnique(int id, string cnic)
    {
        if (id == 0)
        {
            return !hc.evaluationOfProbationers.Any(x => x.cnic == cnic);
        }
        else 
        {
            return !hc.evaluationOfProbationers.Any(x => x.cnic == cnic && x.id != id);
        }
    }
@Html.HiddenFor(model => model.id)@Html.EditorFor(model => model.cnic生成的

HTML 如下:

<input data-val="true" data-val-number="The field id must be a number." data-val-required="The id field is required." id="id" name="id" type="hidden" value="" />

    <div class="form-group">
        <label class="control-label col-md-2" for="CNIC:">CNIC:</label>
        <div class="col-md-10">
            <input class="form-control text-box single-line" data-val="true" data-val-remote="An evaluation of probationer with this cnic already exists. Please provide another cnic." data-val-remote-additionalfields="*.cnic,*.id" data-val-remote-type="POST" data-val-remote-url="/evaluation/cnicExist" data-val-required="The cnic field is required." id="cnic" name="cnic" type="text" value="" />
            <span class="field-validation-valid" data-valmsg-for="cnic" data-valmsg-replace="true"></span>
        </div>
    </div>

在调试时,到目前为止我发现的是[Remote]没有触发cnicExist()。我可能做错的任何想法?

1 个答案:

答案 0 :(得分:1)

您的ID是附加字段,因此大部分是空使用&#34;?&#34; 像这样的事情

[HttpPost]
public JsonResult cnicExist(int? id, string cnic)
{
    return Json(IsUnique(id, cnic));
}
private bool IsUnique(int? id, string cnic)
{
    if (id == 0)
    {
        return false;
    }
    else
    {
        return true;
    }
}