I have been looking at many ASP.Net MVC client side validation ideas including xVal. This doesn't provide a ValidationSummary at the moment so I chose to do an AJAX post which loops through ModelState errors and update a DIV with the error messages on a successful AJAX post.
The problem with this is your ValidationMessage * next to the fields won't get populated. I have come up with an alternative idea which I haven't yet tested as I don't know the full syntax to get it working yet but thought I'd see what you guys thought.
One issue I think may be an issue is that when you post to your Edit/Create Action method in the controller and you want to return a JSON object, I'm not sure that is legal as JSON is used for GET actions only.
If you think its a good idea and are wanting to help please leave an answer and any code snippets to get this working. If you think its a hair brained scheme and can be done better please let me know how.
Controller:
if (!ModelState.IsValid)
{
var err = ModelState.Where(f => f.Value.Errors.Count > 0);
if (Request.IsAjaxRequest())
{
return this.Json(err);
}
else
{
return View(PostedItem);
}
}
View:
$(function() {
$('#createForm').ajaxForm({
success:fillSummary
});
//click events
$('#btnSave').click( function(){
$('#createForm').submit();
});
function fillSummary(data)
{
//Loop through the modelstate errors returned
$.each(data)
{
//Append Summary DIV with error message
//Look for span with the ModelState key name and set it to visible
}
}
<div id="summary">
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.")%>
</div>
<form action="<%=Url.Action("Create") %>" method="post" id="createForm">
<fieldset>
<div>
<label for="Title">Title:</label>
<%= Html.TextBox("Title",Model.Title) %>
<%= Html.ValidationMessage("Title", "*") %>
<span id="val_Title" style="display:none">*</span>
</div>
</form>
<input type="button" value="Save" id="btnSave" />