ASP.NET MVC: How to validate an Ajax form with a specified UpdateTargetID?
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开发者_StackOverflow社区.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
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 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.
精彩评论