如何创建默认的 AjaxOptions
?例如,我有一个带有一些链接的菜单,我想让整个网站使用相同的 loading element
和相同的 error handling
。
@Ajax.ActionLink("Home", "Index", "home", <AjaxOptions>)
new AjaxOptions()
{
OnFailure = "handleError",
LoadingElementId = "loading"
});
但是我有一些更新内容的链接,我想为每个链接设置 UpdateTargetId
。我怎样才能在所有 View 上保留默认的错误处理和加载元素,并为每个链接仅编辑 UpdateTargetId
或 OnSuccess
(或其他属性)?
有点像
@Ajax.ActionLink("home", "Index", "home", ajaxOption.UpdateTargetId = "content")
@Ajax.ActionLink("menu", "Foo", "home", ajaxOption.UpdateTargetId = "side-content")
我想要相当于 jQuery.setup
的东西我可以在其中将默认值设置为 ajax 请求,当我发出 ajax 请求时,我只告诉我要覆盖的参数...
最佳答案
你可以这样做:
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);
}
}
请注意,我在签名中使用了可选参数,以便从多个重载的灵 active 中获益,而无需维护它们。根据需要展开:)
然后按如下方式使用它:
@Ajax.DefaultLink("home", "Index", "home", updateTargetId: "content")
关于c# - 如何为 Razor View 创建默认的 AjaxOptions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5499836/