views:

33

answers:

2

Anyone know of a working sample of jquery axax post with validation messages being returned from the server that highlight the relevant form fields?

Should the form be a partial view? Is it possible to make use of modelstate?

Cheers

+1  A: 

As you've suggested the easiest way is to put the whole form into a partial view and perform an ajax request to a controller action which returns this partial. If you use validation helpers inside this partial, error messages will be shown.

Another alternative is to post to a controller action which puts all error messages inside a JSON array and passes it along to the view. Then using javascript you could loop through the error messages and show them.

Darin Dimitrov
Thanks for the reply. I am more keen on option 1. Do I need to to do anything in the jquery response? $('#subForm').live('submit', function() { $.post($(this).attr('action'), $(this).serialize(), function(data) { //anything needed here? }); return false; });
Chev
A: 

Example attached:

Partial:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<div id="subContent">
<fieldset>
    <legend>Subscribe</legend>    
    <form id="subForm" method="post" action="<%= Url.Action("Subscribe") %>">
        <%= Html.ValidationSummary("Subscribe was unsuccessful. Please correct the errors and try again.") %>
        <input type="text" name="name" id="name" /><%= Html.ValidationMessage("name", "*") %>
        <input type="submit" />
    </form>
</fieldset>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
    $('#subForm').live('submit', function() {
        $.post($(this).attr('action'), $(this).serialize(), function(data) {
            $("#subContent").replaceWith($(data));
        });
        return false;
    });
});
</script>

Controller:

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Subscribe(string name)
        {
            ModelState.AddModelError("name", "You must enter a name");
            return PartialView("SubscribeForm");
        }
Chev