将ajax actionlink转换为引导按钮

时间:2012-05-31 04:00:47

标签: asp.net-mvc twitter-bootstrap

我有一个像这样的ajax actionlink:

 <div style="float:left"> @Ajax.ActionLink("EMPLOYEE", "_PartialEmployeeIndex", "Employee", new AjaxOptions() { UpdateTargetId = "divToUpdate" }) </div>

我通常使用bootstrap来设置我的按钮样式:

  <input class="btn btn-info" type="button" value="Input">

或者像这样

 <button class="btn btn-success" type="submit"> </button>

那么如何将ajax动作链接转换为引导按钮?

我不想将类名放到包含ajax actionlink的div中,因为该按钮显示为黑色字体并带有下划线...

我希望它显示为没有下划线和白色字体的实际按钮

7 个答案:

答案 0 :(得分:14)

您应该能够使用htmlAttributes参数添加所需的任何Bootstrap类:

@Ajax.ActionLink("EMPLOYEE", "_PartialEmployeeIndex", "Employee", new AjaxOptions() { UpdateTargetId = "divToUpdate" }, new { @class = "btn" })

答案 1 :(得分:6)

如果你只想要一个图标,你可以这样做:

    @Ajax.ActionLink(" ", "Delete", new { id = 1 }, new AjaxOptions
                                        {
                                            Confirm = "Are you sure you wish to delete?",
                                            HttpMethod = "Delete",
                                            InsertionMode = InsertionMode.Replace,
                                            LoadingElementId = "div_loading"
                                        }, new { @class = "glyphicon glyphicon-trash" })
  • 名称ationlink不能为null或为空,所以我建议使用空格。

答案 2 :(得分:5)

如果你想要一个真正的Ajax button元素,而不是一个造型黑客,它也可能只涉及一点点。遗憾的是MS尚未选择将ActionButton添加到Html和Ajax帮助程序,因为当您删除重复的私有支持方法时,差异实际上非常小(您只需要ActionButton和{ {1}}方法如下所示。)

最终结果是你可以拥有像ajax动作链接那样触发的真实按钮:

e.g。

GenerateButton

1。创建AjaxHelper扩展

以下代码基于AjaxExtensions类的反编译,因为许多必需的帮助方法未在HtmlHelper上公开。

@Ajax.ActionButton("Delete", "Delete", "document", 
     new { id = ViewBag.Id }, 
     new AjaxOptions() 
     { 
         Confirm="Do you really want to delete this file?", 
         HttpMethod = "Get", 
         UpdateTargetId = "documentlist" }, 
         new { id = "RefreshDocuments" 
     })

2。修改jquery.unobtrusive-ajax.js

jQuery jQuery junery.unobtrusive-ajax.js只需要进行一些小的更改就可以接受新的按钮对象,因为它非常接近开始。首先,选择器需要接受按钮和链接,然后href需要来自一个属性,因此非链接可以提供它(不是严格的浏览器兼容,但现在可以工作)。

public static partial class AjaxExtensions
{
    public static MvcHtmlString ActionButton(this AjaxHelper ajaxHelper, string buttonText, string actionName, string controllerName, object routeValuesBlah, AjaxOptions ajaxOptions, object htmlAttributesBlah)
    {
        // Convert generic objects to specific collections
        RouteValueDictionary routeValues = new RouteValueDictionary(routeValuesBlah);
        RouteValueDictionary htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributesBlah);

        if (string.IsNullOrEmpty(buttonText))
            throw new ArgumentException("Button text must be provided");
        string targetUrl = UrlHelper.GenerateUrl((string)null, actionName, controllerName, routeValues, ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, true);
        return MvcHtmlString.Create(GenerateButton(ajaxHelper, buttonText, targetUrl, AjaxExtensions.GetAjaxOptions(ajaxOptions), htmlAttributes));
    }

    public static string GenerateButton(AjaxHelper ajaxHelper, string linkText, string targetUrl, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
    {
        TagBuilder tagBuilder = new TagBuilder("input");
        tagBuilder.MergeAttribute("value", linkText);
        tagBuilder.MergeAttributes<string, object>(htmlAttributes);
        tagBuilder.MergeAttribute("href", targetUrl);
        tagBuilder.MergeAttribute("type", "button");
        if (ajaxHelper.ViewContext.UnobtrusiveJavaScriptEnabled)
            tagBuilder.MergeAttributes<string, object>(ajaxOptions.ToUnobtrusiveHtmlAttributes());
        else
            tagBuilder.MergeAttribute("onclick", AjaxExtensions.GenerateAjaxScript(ajaxOptions, "Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), {0});"));
        return tagBuilder.ToString(TagRenderMode.Normal);
    }

    private static string GenerateAjaxScript(AjaxOptions ajaxOptions, string scriptFormat)
    {
        string str = ajaxOptions.ToJavascriptString();
        return string.Format((IFormatProvider)CultureInfo.InvariantCulture, scriptFormat, new object[1] { str });
    }

    private static AjaxOptions GetAjaxOptions(AjaxOptions ajaxOptions)
    {
        if (ajaxOptions == null)
            return new AjaxOptions();
        else
            return ajaxOptions;
    }

    public static string ToJavascriptString(this AjaxOptions ajaxOptions)
    {
        StringBuilder stringBuilder = new StringBuilder("{");
        stringBuilder.Append(string.Format((IFormatProvider)CultureInfo.InvariantCulture, " insertionMode: {0},", new object[1]
        {
             ajaxOptions.InsertionModeString()
        }));
        stringBuilder.Append(ajaxOptions.PropertyStringIfSpecified("confirm", ajaxOptions.Confirm));
        stringBuilder.Append(ajaxOptions.PropertyStringIfSpecified("httpMethod", ajaxOptions.HttpMethod));
        stringBuilder.Append(ajaxOptions.PropertyStringIfSpecified("loadingElementId", ajaxOptions.LoadingElementId));
        stringBuilder.Append(ajaxOptions.PropertyStringIfSpecified("updateTargetId", ajaxOptions.UpdateTargetId));
        stringBuilder.Append(ajaxOptions.PropertyStringIfSpecified("url", ajaxOptions.Url));
        stringBuilder.Append(ajaxOptions.EventStringIfSpecified("onBegin", ajaxOptions.OnBegin));
        stringBuilder.Append(ajaxOptions.EventStringIfSpecified("onComplete", ajaxOptions.OnComplete));
        stringBuilder.Append(ajaxOptions.EventStringIfSpecified("onFailure", ajaxOptions.OnFailure));
        stringBuilder.Append(ajaxOptions.EventStringIfSpecified("onSuccess", ajaxOptions.OnSuccess));
        --stringBuilder.Length;
        stringBuilder.Append(" }");
        return ((object)stringBuilder).ToString();
    }

    public static string InsertionModeString(this AjaxOptions ajaxOptions)
    {
        switch (ajaxOptions.InsertionMode)
        {
            case InsertionMode.Replace:
                return "Sys.Mvc.InsertionMode.replace";
            case InsertionMode.InsertBefore:
                return "Sys.Mvc.InsertionMode.insertBefore";
            case InsertionMode.InsertAfter:
                return "Sys.Mvc.InsertionMode.insertAfter";
            default:
                return ((int)ajaxOptions.InsertionMode).ToString((IFormatProvider)CultureInfo.InvariantCulture);
        }
    }

    public static string EventStringIfSpecified(this AjaxOptions ajaxOptions, string propertyName, string handler)
    {
        if (string.IsNullOrEmpty(handler))
            return string.Empty;
        return string.Format((IFormatProvider)CultureInfo.InvariantCulture, " {0}: Function.createDelegate(this, {1}),",
            new object[2]
              {
                propertyName,
                handler
              });
    }

    public static string PropertyStringIfSpecified(this AjaxOptions ajaxOptions, string propertyName, string propertyValue)
    {
        if (string.IsNullOrEmpty(propertyValue))
            return string.Empty;
        string str = propertyValue.Replace("'", "\\'");
        return string.Format((IFormatProvider)CultureInfo.InvariantCulture, " {0}: '{1}',",
            new object[2]
              {
                propertyName,
                str
              });
    }
}

*注意:这是在回答日期使用最新版本的所有内容(MVC 5)

答案 3 :(得分:0)

如果您不想担心为每个Bootstrap元素分配适当的类,请查看TwitterBootstrapMVC

在带有ajax链接的示例中,您可以编写如下内容:

@Ajax.ActionLink("EMPLOYEE", "_PartialEmployeeIndex", "Employee", ).AjaxOptions(new AjaxOptions() { UpdateTargetId = "divToUpdate" })

答案 4 :(得分:0)

添加到Terry答案,如果要将html添加到按钮,最好的方法是使用Javascript附加html代码。 Ajax.Actionlink的linkText参数会自动编码您提供的任何文本,除了编写自己的帮助程序之外,您无法做任何事情(除了编写自己的帮助程序)。

像JQuery append或prepend这样的东西会起作用。

<div> 
@Ajax.ActionLink("EMPLOYEE", "_PartialEmployeeIndex", "Employee", new AjaxOptions() { UpdateTargetId = "divToUpdate" }, new { @class = "btn btn-default my-custom-class" }) 
</div>

<script>
    $(".my-custom-class").prepend("<span class=\"glyphicon glyphicon-pencil\"></span>&nbsp; ");
</script>

答案 5 :(得分:0)

一种替代方法是使用Ajax.BeginForm,它允许您直接输入HTML。假设您还没有表单。

@using (Ajax.BeginForm("EMPLOYEE", "_PartialEmployeeIndex", "Employee", new AjaxOptions() { UpdateTargetId = "divToUpdate" }))
{
    <button type="submit" id="EmployeeButton" title="Employee" aria-label="Employee Button">
        <span class="glyphicon glyphicon-trash"></span>
    </button>
}

答案 6 :(得分:-1)

@Ajax.ActionLink(" ", "EditUser/" + Model.Id, null, new AjaxOptions { 
      OnSuccess = "userEditGet", 
      HttpMethod = "post", 
      LoadingElementId = "ajaxLoader" }
 ,new { @class = "btn btn-default glyphicon glyphicon-edit" })