我有一個示例應用程序,試圖學習jQuery驗證並在此場景中提交表單。ASP.Net MVC 2 - jQuery驗證和表單提交 - DataAnnotations
該頁面有一個文本框(每個類信封的EnvelopeID)。如果點擊提交按鈕,文本框是空的,那麼我想顯示一條錯誤消息。如果它不是空的,那麼我想發佈一個Ajax請求到GetData操作。該操作返回部分視圖(值1或2)或錯誤字符串。
問題:
- 客戶端驗證不在這裏發生。
- 我如何使
$(form).submit
堅持jQuery驗證,並且不會發布數據如果爲空?我可以檢查文本框是空的或不張貼(手動),但我想使用正確的方法。
這個相同的例子適用於MSAjax和驗證沒有任何問題。
母版頁頭
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.validate.min.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/MicrosoftMvcJQueryValidation.js") %>"></script>
類:
namespace PartialViews.Models
{
public class Envelope
{
[Required(ErrorMessage="Envelope ID is required!")]
public string EnvelopeID { get; set; }
}
}
數據操作:
[HttpPost]
public ActionResult GetData(Envelope envelope)
{
ActionResult result = null;
if (ModelState.IsValid)
{
Information myInfo = newInformation();
if (envelope.EnvelopeID == "1")
{
result = View("TQ1PV", myInfo); //partial view
}
elseif (envelope.EnvelopeID == "2")
{
result = View("TQ2PV", myInfo); //partial view
}
else
{
result = Content("Error");
}
}
else
{
result = View("index", envelope);
}
return result;
}
指數操作:
public Action Result Index()
{
return View();
}
上查看JS - 指數
<script type="text/javascript">
$(function() {
//onload
$("#evid").focus();
$("form[name='EVIDForm']").submit(function() {
var action = $(this).attr('action');
var evid = $("#evid").val();
var tdata = $(this).serialize();
alert(tdata);
$message = $("#resultDiv");
$message.html('').removeClass("red");
$.ajax({
cache: false,
type: "post",
url: action,
data: tdata,
dataType: "html",
error: function (xhr, ajaxOptions, thrownError){
alert('system error');
},
success: function(data){
if (data == 'Error')
$message.html("No such EV ID found!").addClass("red");
else
$message.html(data);
}
});
return false;
});
});
</script>
上查看HTML - 指數:
<% Html.EnableClientValidation(); %>
<%= Html.ValidationSummary() %>
<% using (Html.BeginForm("GetData", "Info", FormMethod.Post, new {name = "EVIDForm" }))
{%>
<%= Html.LabelFor(model => model.EnvelopeID) %>
<%= Html.TextBoxFor(model => model.EnvelopeID, new { maxlength = "8"})%>
<%= Html.ValidationMessageFor(model => model.EnvelopeID,"*") %>
<br /><br />
Correct EVIDs are 1 and 2. All other entries will result in an error.
<br /><br />
<input type="submit" value="submit" />
<%} %>
<div id="resultDiv" style="margin-top: 20px;"></div>
感謝
我具有幾乎相同的問題,因爲在所描述的帖子@vandalo鏈接。看起來,客戶端驗證在未提交表單的情況下不起作用。但如果我必須提交表單驗證不再是客戶端....我沒有收到我的問題在這裏回答:'http://stackoverflow.com/questions/4172319/inline-client-side-validation -with-mvc-and-jquery /' – Lorenzo 2010-11-16 14:13:30
@Lorenzo:表單未提交。您可以嘗試在接收帖子的控制器中設置斷點。它永遠不會觸發。唯一的問題是(只有第一次,直到你不點擊按鈕)客戶端驗證似乎從一開始就沒有觸發。 – LeftyX 2010-11-16 14:40:23
@vandalo:如果你使用提琴手或螢火蟲,你可以看到提交給服務器 – Lorenzo 2010-11-16 14:47:11