У меня возникают некоторые проблемы с проверкой в моем проекте 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" });
}
}
}
My View
@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;
});
});