我有一个简单的一页应用程序来向用户发送电子邮件。我有 3 个字段,分别是姓名、电子邮件和电话号码。该代码似乎适用于输入按钮,会触发验证并抛出正确的错误消息。但我更倾向于在我的 UI 中使用 anchor 标记 (ActionLink)。当我单击 anchor 标记(使用 jQuery)时,数据仍然会发布,但验证不会触发。有什么我遗漏的或者有更好的方法吗?
我用过this发帖作为引用。
型号
public class Contact
{
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
[Required(ErrorMessage = "Email is required")]
public string Email { get; set; }
[Required(ErrorMessage = "Phone is required")]
public string PhoneNumber { get; set; }
}
查看
<div>
@Html.TextBoxFor(model => model.Name, new { @class = "form-control", placeholder="Name" })
@Html.ValidationMessageFor(model=>model.Name)
</div>
<div>
@Html.TextBoxFor(model => model.Email, new { @class = "form-control", placeholder="Email" })
@Html.ValidationMessageFor(model=>model.Email)
</div>
<div>
@Html.TextBoxFor(model => model.PhoneNumber, new { @class = "form-control", placeholder="Phone" })
@Html.ValidationMessageFor(model=>model.PhoneNumber)
</div>
<div>
<input type="submit" value="Give me Free Advice" />
<div class="btn">
@Html.ActionLink("I want free advice", "designerhome")
</div>
</div>
<script>
$(function () {
$('.btn').click(function (e) {
$.post("/campaign/designerhome", { Name: $("#Name").val(), Email: $("#Email").val(), PhoneNumber: $("#Phone").val() }, function (result) {
//do whatever with the response
if (result.status == true) {
alert('Email submitted successfully');
}
});//end of post
});//end of click
});
</script>
Controller
[HttpPost]
public ActionResult designerhome(Contact contact)
{
if (ModelState.IsValid)
{
}
return View("Advert1");
}
最佳答案
我们有一些原因导致验证不起作用
<强>1。检查网络配置中的应用程序设置
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
如果您想运行客户端验证,则两者都应该为 true。
<强>2。在您的代码中似乎您没有使用表单标签,因为它已发布在问题中
表单标签是验证所必需的
<强>3。 Jquery 在布局页面上未正确引用
请检查布局页面上的以下 jquery 引用
jquery.unobtrusive*.js
jquery.validate*.js
希望对您有帮助。
关于c# - MVC4 验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31157717/