views:

50

answers:

1

I'm trying to figure out how to show validation errors after a user submits an Ajax form that has its UpdateTargetID property set.

I'm stumped on how to update the Ajax form with the validation errors without returning the Create PartialView into the results div. If the form is valid, then it should return the Records PartialView.

Create.ascx

<%  Using Ajax.BeginForm("Create", 
                         "Record", 
                         New Record With {.UserID = Model.UserID}, 
                         New AjaxOptions With {
                             .UpdateTargetId = "results", 
                             .LoadingElementId = "loader"
                         })%>        
    Date Located
    <%= Html.TextBoxFor(Function(model) model.DateLocated)%>
    <%= Html.ValidationMessageFor(Function(model) model.DateLocated) %>

    Description
    <%= Html.TextBoxFor(Function(model) model.Description)%>
    <%= Html.ValidationMessageFor(Function(model) model.Description) %>

    <input id="btnSave" type="submit" value="Create" />          

    <span id="loader" class="loader">Saving...</span>
<%End Using%>

Records.ascx

<div id="results">
    ...
</div>

RecordController.vb

Function Create(ByVal newRecord As Record) As ActionResult
    ValidateRecord(newRecord)

    If Not ModelState.IsValid Then
        Return PartialView("Create", newRecord)
    End If

    _repository.Add(newRecord)
    _repository.Save()

    Dim user = _repository.GetUser(newRecord.UserID)
    Return PartialView("Records", user)
End Function
+2  A: 

You cannot show validation errors if you don't refresh the part of the DOM containing the elements with validation messages which in your case is the form. So you could to put the entire form and the result div in a partial which will be refreshed. You may take a look at this post as well.

Darin Dimitrov