【发布时间】:2015-07-01 09:37:03
【问题描述】:
我有一个简单的 1 页应用程序来向用户发送电子邮件。我有 3 个字段用于姓名、电子邮件和电话号码。该代码似乎与输入按钮一起使用,验证触发并抛出正确的错误消息。但我更倾向于在我的 UI 中使用锚标记 (ActionLink)。当我单击锚标记(使用 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>
控制器
[HttpPost]
public ActionResult designerhome(Contact contact)
{
if (ModelState.IsValid)
{
}
return View("Advert1");
}
【问题讨论】:
-
为了避免请求被重定向到 GET 请求。在锚的 onClick() 方法中绑定 e.preventDefault()。
标签: c# jquery asp.net asp.net-mvc asp.net-mvc-4