ASP.NET MVC: How to validate an Ajax form with a specified UpdateTargetID?

Posted by Bryan Roth on Stack Overflow See other posts from Stack Overflow or by Bryan Roth
Published on 2010-04-13T20:35:16Z Indexed on 2010/04/14 6:33 UTC
Read the original article Hit count: 384

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about ajax-form