How do I create a default AjaxOptions
? For example, I have a menu with some links, I want to make the entire website to use the same loading element
and same error handling
.
@Ajax.ActionLink("Home", "Index", "home", <AjaxOptions>)
new AjaxOptions()
{
OnFailure = "handleError",
LoadingElementId = "loading"
});
But then I have some links that update the content and I want to set UpdateTargetId
for each of those links. How can I keep a default error handling and loading element on all the views and edit only UpdateTargetId
or OnSuccess
(or another property) for each link?
Something like
@Ajax.ActionLink("home", "Index", "home", ajaxOption.UpdateTargetId = "content")
@Ajax.ActionLink("menu", "Foo", "home", ajaxOption.UpdateTargetId = "side-content")
I want something equivalent to jQuery.setup
where I can set the default values to ajax requests and when I make an ajax request I only tell the parameters I want to override...
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"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With