When following most examples and tutorials online, you are often advised to return a view using your HttpPost
action method. This typically involves setting the 'UpdateTargetId' and InsertionMode
properties on the AjaxOptions
object.
However, if your intention is to return data and interact with it through JavaScript, this approach may not suffice. Instead, you will need to utilize the OnSuccess
method of the AjaxOptions
object.
While the documentation for OnSuccess
may seem lacking in information, it actually requires the name of a JavaScript function available on the current page to work effectively. This function will be invoked callback-style, so ensure that you adhere to the correct syntax for your specific scenario.
Below is a demonstration to illustrate these concepts:
Controller Methods:
<HttpGet>
Function AjaxIndex() As ActionResult
Dim model As AjaxFormModel = New AjaxFormModel
' Customize the AjaxFormModel as needed.
Return View(model)
End Function
<HttpPost>
Function AjaxIndex(ByVal model As AjaxFormModel) As JsonResult
Dim result As AjaxFormResult = Nothing
' Populate the AjaxFormResult with relevant properties such as .MessageType and .Payload.
' TODO: Make sure to create a new object to pass to the `JsonResult`.
Return New JsonResult With {.Data = result, .JsonRequestBehavior = JsonRequestBehavior.AllowGet}
End Function
HTML
Using Ajax.BeginForm("AjaxIndex", "Bootstrap",
routeValues:=Nothing,
ajaxOptions:=New AjaxOptions With {.HttpMethod = "POST",
.OnSuccess = "updateAjaxForm"},
htmlAttributes:=Nothing)
@<text>
<div class="row">
<div class="col-sm-12" id="UnknownError_message">
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="text" name="Name" />
<div id="Name_message"></div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" class="btn btn-default" value="Save" />
</div>
</div>
</text>
End Using
JavaScript / jQuery
<script type="text/javascript">
function updateAjaxForm(data) {
// The data parameter contains a processed JavaScript object. Thanks to MVC!
var messageElement = $('#UnknownError_message');
switch (data.MessageType) {
case 0: // Error message
messageElement.html('Error: ' + data.Message);
break;
case 1: // Textual message
messageElement.html('Info: ' + data.Message);
break;
default:
messageElement.html('Unexpected Error.');
}
}
</script>