使用[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()
。我可能做错的任何想法?
答案 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;
}
}