Bru*_*oLM 9 c# ajax razor asp.net-mvc-3
如何创建默认值AjaxOptions
?例如,我有一个带有一些链接的菜单,我想让整个网站使用相同loading element
和相同error handling
.
@Ajax.ActionLink("Home", "Index", "home", <AjaxOptions>)
new AjaxOptions()
{
OnFailure = "handleError",
LoadingElementId = "loading"
});
Run Code Online (Sandbox Code Playgroud)
但后来我有一些更新内容的链接,我想UpdateTargetId
为每个链接设置.如何在所有视图上保留默认错误处理和加载元素,仅为每个链接编辑UpdateTargetId
或OnSuccess
(或其他属性)?
就像是
@Ajax.ActionLink("home", "Index", "home", ajaxOption.UpdateTargetId = "content")
@Ajax.ActionLink("menu", "Foo", "home", ajaxOption.UpdateTargetId = "side-content")
Run Code Online (Sandbox Code Playgroud)
我想要的东西等同于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);
}
}
Run Code Online (Sandbox Code Playgroud)
注意我在签名中使用可选参数,以便从多个重载的灵活性中受益,而不会对维护它们造成麻烦.根据需要展开:)
然后使用它如下:
@Ajax.DefaultLink("home", "Index", "home", updateTargetId: "content")
Run Code Online (Sandbox Code Playgroud)
我发现继承AjaxOptions类并在我的视图中实例化DefaultAjaxOptions更容易.这意味着如果您有其中一个没有创建单独的扩展方法,您可以将它用于Ajax.ImageActionLink之类的东西.看下面的例子,我唯一需要改变的就是目标,所以我允许将它传递给构造函数.
public class DefaultAjaxOptions : AjaxOptions
{
public DefaultAjaxOptions(string target)
{
InsertionMode = InsertionMode.Replace;
UpdateTargetId = target;
OnBegin = "BeginLoadingSection()";
OnFailure = "FailureLoadingSection()";
OnSuccess = "SuccessLoadingSection()";
}
}
Run Code Online (Sandbox Code Playgroud)
然后在视图中使用:
@{ var ajaxOptions = new DefaultAjaxOptions("name-of-content-div"); }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2638 次 |
最近记录: |