创建一个名为的自定义视图
AjaxLinksPartial.cshtml
@Scripts.Render("~/bundles/jquery") @*You need this included, probably in your main layout*@
@Scripts.Render("~/bundles/jqueryval")
<div id ="Target"></div>
@{foreach (var link in Model.LinkItems)
{
@Ajax.ActionLink(link.Text, link.Action, link.Controller, null, Model.AjaxOptions, Model.HtmlAttrbs)
}
}
使用支持模型 AjaxLinks
public class AjaxLinks
{
public List<LinkItem> LinkItems { get; set; }
public AjaxOptions AjaxOptions { get; set; }
public Dictionary<string, Object> HtmlAttrbs { get; set; }
public AjaxLinks(AjaxOptions options, Dictionary<string, Object> htmlAttrbutes)
{
LinkItems = new List<LinkItem>();
this.AjaxOptions = options;
this.HtmlAttrbs = htmlAttrbutes;
}
}
public class LinkItem
{
public string Text { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public LinkItem(string Text, string Controller, string Action)
{
this.Text = Text;
this.Controller = Controller;
this.Action = Action;
}
}
在控制器中按如下方式使用它
var htmlAttributes = new Dictionary<string, Object>();
htmlAttributes.Add("class", "linkstyling class");
var ajaxOptions = new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "Target", HttpMethod = "POST"};
var links = new AjaxLinks(ajaxOptions, htmlAttributes);
links.LinkItems.Add(new LinkItem("About","Home","About"));
并在另一个视图中渲染它
@Html.Partial("AjaxLinksPartial", Model)
主要的缺点是这不是样式和其他问题的清晰分离。如果您能够使用 HtmlHelpers 干净地重新制作它,我会非常感兴趣。有的话PM我或评论。