How to create a default AjaxOptions for Razor Views? How to create a default AjaxOptions for Razor Views? ajax ajax

How to create a default AjaxOptions for Razor Views?


You could do something like:

public static class AjaxExtensions{    public static IHtmlString DefaultLink(this AjaxHelper helper, string text,        string action, string controller, string updateTargetId = "",         string onSuccess = "")    {        // Build your link here eventually using         // the arguments passed        var options = new AjaxOptions        {            OnSuccess = onSuccess,            UpdateTargetId = updateTargetId,            OnFailure = "handleError",            LoadingElementId = "loading"            // etc...        }        // return a normal ActionLink passing your options        return helper.ActionLink(text, action, controller, options);    }}

Note I'm using optional parameters in the signature to benefit from the flexibility of multiple overloads without the nuisance of maintaining them. Expand as needed :)

Then just use it as follows:

@Ajax.DefaultLink("home", "Index", "home", updateTargetId: "content")


I found it easier to inherit the AjaxOptions class and instantiate DefaultAjaxOptions in my view. This means you can use it for things like Ajax.ImageActionLink if you have one of those without creating a separate extension method. See example below, the only thing I needed to change was the target so I allowed this to be passed into the constructor.

public class DefaultAjaxOptions : AjaxOptions{    public DefaultAjaxOptions(string target)    {        InsertionMode = InsertionMode.Replace;        UpdateTargetId = target;        OnBegin = "BeginLoadingSection()";        OnFailure = "FailureLoadingSection()";        OnSuccess = "SuccessLoadingSection()";    }}

then in the view use:

@{ var ajaxOptions = new DefaultAjaxOptions("name-of-content-div"); }