[英]MVC 5 remote validation not fired
我正在尝试在 MVC 中实现远程验证。 我已经阅读了一些已经在这里发布的教程和问题,但没有答案。
控制器 :
public class GroupsController: Controller
{
[HttpPost]
public ActionResult TestRemoteValidation(string Name)
{
return Json(false);
}
}
看法 :
@using (Html.BeginForm("Index", "Defaults", FormMethod.Post))
{
@Html.TextBoxFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
<input type="submit" class="btn btn-primary" value="Enregistrer" />
}
和型号:
public class Group
{
[Key]
public int Id { get; set; }
[Display(Name = "Nom du Groupe")]
[Required]
[Remote("TestRemoteValidation", "Groups", HttpMethod = "POST", ErrorMessage = "Remote fired")]
//[CustomRemoteValidation("TestRemoteValidation", "Groups", AdditionalFields = "Id")]
public string Name { get; set; }
public virtual ICollection<ApplicationUser> ApplicationUsers { get; set; }
}
生成的 HTML 代码:
<input data-val="true" data-val-remote="Remote fired" data-val-remote-additionalfields="*.Name" data-val-remote-type="POST" data-val-remote-url="/Groups/TestRemoteValidation" data-val-required="Le champ Nom du Groupe est requis." htmlAttributes="{ class = form-control }" id="Name" name="Name" type="text" value="" />
我使用Metadata
是因为它是一个实体--> 不是问题,我检查了另一个 ViewModel,结果是一样的。
[Required]
和[StringLength(10)]
被触发。 当我在TestRemoteValidation
放置断点时,没有任何反应。
例如,我可以使用自定义远程属性类和Model.IsValid
覆盖来执行远程验证,但我不明白为什么这种方式不起作用。 任何的想法?
假设Vehicule
是@model
中使用的@model
@model Vehicule
那么控制器应该期望该模型
public class DefaultsController : Controller {
[HttpGet]
public ActionResult Index() {
var model = new Vehicule();
return View(mdoel);
}
[HttpPost]
public ActionResult Index(Vehicule model) {
if(ModelState.IsValid) {
//...do something
//..possible redirect
}
//if we get this far something is wrong with data
return View(model);
}
}
当从请求绑定模型时,模型绑定器将考虑验证。
添加
[允许匿名]
[HttpPost] public ActionResult TestRemoteValidation(string Name)
请确保您在视图中包含以下库并按正确顺序
<script src="~/scripts/jquery.js"></script>
<script src="~/scripts/jquery.validate.js"></script>
<script src="~/scripts/jquery.validate.unobtrusive.js"></script>
这些库是远程验证工作所必需的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.