I am having some challenges with validation in my ASP.NET MVC3 project when using jQuery and AJAX to post back data from a partial view.
Adding validation to the NoteText field within my partial view results in “$(‘#noteAdd’).submit” event failing to trigger and my form posting directly to the controller. Removing the validation results in the expected behaviour.
I was hoping somebody might be able to shed some light over what’s happening here, why it’s happening and my provide some advice on how to resolve the issue and I’ve included my partial, controller, JS and view below.
My Partial
[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; }
}
}
My Controller
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;
});
});
put partial keyword on your class :