Handling AJAX Postbacks using the UmbracoApiController
Form Validation using AJAX Postbacks
While using Umbraco in MVC we often need to validate data without performing a complete post back to the page. By sending a partial post back we can interact with the server side logic to retrieve desired results without a complete refresh.
Using standalone MVC in ASP.net we can easily communicate with a method in a controller class tagged with the [HttpPost] attribute, but Umbraco adds an extra layer of complexity. Enter the UmbracoApiController.
UmbracoApiController
To get up and running you'll need to ensure that your controller inherits the UmbracoApiController, which bridges the gap between the Umbraco and your MVC controller. A few points worth noting:
- Accept verbs, Route and HttpPost attributes needs to be set correctly.
- The type of the controller method parameters needs to be prefixed with [System.Web.Http.FromBody] - An attribute that specifies that an action parameter comes only from the body of the incoming HttpRequestMessage.
Consider the following example:
public class FormValidationController : UmbracoApiController { [AcceptVerbs("GET", "POST")] [HttpPost] [Route("FormValidation/{field}")] public bool ValidateField([System.Web.Http.FromBody]string field) { var result = false; //Your code here return result; } }
JQuery AJAX Request
In the script making the postback call the URL should be prefixed with '/Umbraco/Api/' as shown below:
function Validate(obj, output){ $.post('/Umbraco/Api/FormValidation/Validate/', { "": obj.val() }) .success(function (data) { output.val(data); }); }
The example takes care of the basic exchange of data but could be extended to meet your specific needs.