您正在寻找的东西在 Asp.Net MVC 中称为“远程验证”。
首先确保在您的 web.config 中启用客户端验证。
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
第二在您的控制器中创建将返回 JsonResult 的验证方法。
public class ValidationController : Controller
{
public JsonResult CheckValidIP(string clientIP)
{
//your validation code here
if (!_repository.AllowIp(clientIP))
return Json(true, JsonRequestBehavior.AllowGet);
else
return Json(false, JsonRequestBehavior.AllowGet);
}
}
第三 在模型中插入[Remote] 属性。第一个参数是Action,第二个参数是Controller。
public class CreateUserModel : EditUserModel {
[Remote("CheckValidIP", "Validation")]
public override string ClientIP { get; set; }
}
最后但同样重要的是,您必须使用 Html Helper 来生成带有 javascript 的 html 等等。
@model RemoteValidation.Models.SampleModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Remote Validation</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.ClientIp, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ClientIp, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ClientIp, "", 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>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
这是一个正在运行的示例应用程序,只有远程验证,这里 => https://github.com/ricardodemauro/AspNetMVCRemoteValidation
RemoteAttribute 类创建一个字符串,该字符串表示用于调用基于服务器的验证的 URL。然后,ASP.NET MVC 框架为 URL 提交 JSON 编码的 GET 请求。
在本例中,如果用户在客户端 IP 文本输入框中输入“127.0.0.1”,客户端将请求以下 URL:
/Validation/CheckValidIP?ClientIP=127.0.0.1
在这里您可以找到更多详细信息 => https://msdn.microsoft.com/en-us/library/gg508808(vs.98).aspx