我在驗證時使用jquery將表單數據發佈到控制器時遇到了一些麻煩。嘗試添加ajax post函數時MVC3驗證失敗
此代碼的工作原理和驗證發生很好,如果我不使用jQuery的發佈。
<div id="window">
@using (Html.RequiredFieldsMessage()){}
@using (Html.BeginForm("","",FormMethod.Post,new{id="card-payment"}))
{
@Html.ValidationSummary(true, "Please fix the errors below.")
<div class="inputForm no-border">
<div class="fr">
@Html.LabelFor(model => model.DpsPaymentModel.CardHolderName)
@Html.EditorFor(model => model.DpsPaymentModel.CardHolderName)
@Html.ValidationStyledMessageFor(model => model.DpsPaymentModel.CardHolderName, false)
</div>
<div class="fr">
@Html.LabelFor(model => model.DpsPaymentModel.CardNumber)
@Html.EditorFor(model => model.DpsPaymentModel.CardNumber)
@Html.ValidationStyledMessageFor(model => model.DpsPaymentModel.CardNumber, false)
</div>
<div class="fr">
@Html.LabelFor(model => model.DpsPaymentModel.DateExpiry)
@Html.EditorFor(model => model.DpsPaymentModel.DateExpiry)
@Html.ValidationStyledMessageFor(model => model.DpsPaymentModel.DateExpiry, false)
</div>
<div class="fr">
@Html.LabelFor(model => model.DpsPaymentModel.Cvc2)
@Html.EditorFor(model => model.DpsPaymentModel.Cvc2)
@Html.ValidationStyledMessageFor(model => model.DpsPaymentModel.Cvc2, false)
</div>
<div class="fr">
@Html.LabelFor(model => model.DpsPaymentModel.Amount)
@Html.EditorFor(model => model.DpsPaymentModel.Amount)
@Html.ValidationStyledMessageFor(model => model.DpsPaymentModel.Amount, false)
</div>
<div class="fr">
<button type="submit" id="process-payment">Submit</button>
</div>
</div>
}
</div>
如果我將此添加到我的視圖。驗證總是返回爲真。我的html不是以相同的視圖加載正確的jQuery驗證腳本的部分視圖。
$("#process-payment").click(function() {
event.preventDefault();
var form = $("#card-payment");
$.validator.unobtrusive.parse(form);
if (form.validate()) {
console.log("valid");
$.ajax({
url: '/payment/processcardpayment',
type: "POST",
data: form.serialize(),
success: function (data) {
console.log(data);
},
error: function (jqXhr, textStatus, errorThrown) {
alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
},
complete: function() {
// $("#ProgressDialog").dialog("close");
}
});
} else {
console.log("invalid");
}
});
再次感謝你! – 2012-02-26 23:26:46
非常感謝它的幫助 – Mary 2014-06-08 07:29:33