如何做到这一点?
例如在我的模型中我有
[Required]
[DataType(DataType.EmailAddress)]
[RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect email")]
public string EmailTo { get; set; }
我目前测试的新 Controller 是
[HttpPost]
public EmptyResult SendAgreementEmail(AgreementReportModel model)
{
bool t = ModelState.IsValid;
return new EmptyResult();
}
即使 emailto 为 null,ModelState.IsValid 也是有效的。
和js函数
function SendEmailWithJquery(offerID, agreementOfferID, customerID) {
var emailTo = document.getElementById('txtEmailTo').value;
var emailSubject = document.getElementById('txtEmailSubject').value;
var emailBody = document.getElementById('txtEmailBody').value;
var sendData = {
OfferID: offerID,
AgreementOfferID: agreementOfferID,
CustomerID: customerID,
EmailTo: emailTo,
EmailSubject: emailSubject,
EmailBody: emailBody
};
$.ajax({
url: "/Agreement/SendAgreementEmail",
type: "POST",
data: JSON.stringify(sendData),
dataType: 'json',
contentType: 'application/json',
success: function (data, textStatus, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
};
是否可以使用 json 对象和强类型 View 来验证服务器端的 Controller ?
最佳答案
我使用了与您相同的代码,服务器端验证对我来说工作得非常好。为了简单起见,我删除了所有属性,除了电子邮件属性(因为它导致了主要问题)。
模型 -
public class AgreementReportModel
{
[Required]
[DataType(DataType.EmailAddress)]
[RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect email")]
public string EmailTo { get; set; }
}
Controller Action -
public class AgreementController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public EmptyResult SendAgreementEmail(AgreementReportModel model)
{
bool t = ModelState.IsValid;
return new EmptyResult();
}
}
索引 View -
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function SendEmailWithJquery() {
var sendData = {
EmailTo: ''
};
$.ajax({
url: "/Agreement/SendAgreementEmail",
type: "POST",
data: JSON.stringify(sendData),
dataType: 'json',
contentType: 'application/json',
success: function (data, textStatus, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
};
</script>
<input type="button" value="Click" onclick="SendEmailWithJquery()" />
当我启动 EmailTo : 'rami@gmail.com 时,我得到 ModelState.IsValid 为真。
当我启动 EmailTo : null 或 EmailTo : '' 时,我得到 ModelState.IsValid 为 false。
下一步做什么:
- 检查您的其他数据类型,它们可能是罪魁祸首。
- 检查您的 JavaScript 输入检索,document.getElementById,它可能会为您提供空值。
- 检查可能导致问题的代码的其他部分,可能是 Action 过滤器等代码。
关于javascript - jquery ajax 发布请求的 mvc 服务器端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21457468/