0
使用jQuery和AJAX從部分視圖回發數據時,我在ASP.NET MVC3項目中驗證時遇到了一些問題。使用jQuery和Ajax在部分視圖中回發表單時的驗證問題
將驗證添加到我的分部視圖中的NoteText字段將導致「$('#noteAdd')。submit」事件無法觸發,並且我的表單直接發佈到控制器。以預期的行爲去除驗證結果。
我希望有人能夠揭示這裏發生的事情,爲什麼會發生,我提供了一些關於如何解決問題的建議,並且我已經包含了我的部分,控制器,JS和下面的視圖。
我偏
[Bind(Include = "NoteId,NoteText,Date,SourceId,Username,TypeId,ItemId,Processed")]
[MetadataType(typeof(NotePartial_Validation))]
public class NotePartial
{
public int NoteId { get; set; }
public string NoteText { get; set; }
public DateTime? Date { get; set; }
public int? Source { get; set; }
public string Username { get; set; }
public int ItemId { get; set; }
public int TypeId { get; set; }
public IEnumerable<NotePartial> ExistingNotes { get; set; }
}
public class NotePartial_Validation
{
[HiddenInput(DisplayValue = false)]
public int NoteID { get; set; }
[Required]
public string NoteText { get; set; }
[HiddenInput(DisplayValue = false)]
public int ItemId { get; set; }
[HiddenInput(DisplayValue = false)]
public int TypeId { get; set; }
}
}
我的控制器
public class NoteController : Controller
{
[HttpPost]
public ActionResult Create(NotePartial model)
{
try
{
NoteMethods.CreateNote(model.NoteText, SessionManager.Current.ActiveUser.Username, model.ItemId, SessionManager.Current.ActiveUser.Company);
return Json(new { s = "Success" });
}
catch (NoPermissionException)
{
return Json(new { s = "No permission" });
}
}
}
我查看
@model EF.NotePartial
@{using (Html.BeginForm("Create", "Note", new { area = "" }, FormMethod.Post, new { id = "noteAdd" }))
{
@Html.TextAreaFor(m => m.NoteText, new { @class = "note-input" }) //note-input
@Html.ValidationMessageFor(model => model.NoteText)
<input type="submit" value="Send" />
}}
<script type="text/javascript">
$(function() {
$('#noteAdd').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
error: function (xhr, ajaxOptions, thrownError) {
alert('An error occured when processing this request:\r\n\r\n' + thrownError);
},
success: function (result) {
alert(result.s);
}
});
// it is important to return false in order to
// cancel the default submission of the form
// and perform the AJAX call
return false;
});
});
我怎麼錯過了,我不知道:)謝謝。你有關於代碼的其他意見嗎?我對MVC比較陌生,想知道這是否是實現這一目標的最佳方式? – Nick
@Nick好吧,我可以告訴你的一件事是,你不需要把每個屬性放在你的部分類中,它處理驗證。只要把你需要驗證的。 – tugberk
謝謝 - 關於上面的代碼的一件事。如果驗證失敗,表單仍然提交。如果成功,則表單將被回發,並將JSON文件推送到瀏覽器。你有什麼建議嗎? – Nick