Html.ActionLink 作为按钮或图像,而不是链接

发布于 2024-07-14 11:18:07 字数 69 浏览 9 评论 0 原文

在最新 (RC1) 版本的 ASP.NET MVC 中,如何让 Html.ActionLink 呈现为按钮或图像而不是链接?

In the latest (RC1) release of ASP.NET MVC, how do I get Html.ActionLink to render as a button or an image instead of a link?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

墨落成白 2024-07-21 11:18:07

我喜欢像这样使用 Url.Action() 和 Url.Content() :

<a href='@Url.Action("MyAction", "MyController")'>
    <img src='@Url.Content("~/Content/Images/MyLinkImage.png")' />
</a>

严格来说,Url.Content 仅用于路径,并不是您问题答案的一部分。

感谢 @BrianLegg 指出这应该使用新的 Razor 视图语法。 示例已相应更新。

I like to use Url.Action() and Url.Content() like this:

<a href='@Url.Action("MyAction", "MyController")'>
    <img src='@Url.Content("~/Content/Images/MyLinkImage.png")' />
</a>

Strictly speaking, the Url.Content is only needed for pathing is not really part of the answer to your question.

Thanks to @BrianLegg for pointing out that this should use the new Razor view syntax. Example has been updated accordingly.

抹茶夏天i‖ 2024-07-21 11:18:07

响应较晚,但您可以保持简单并将 CSS 类应用于 htmlAttributes 对象。

<%= Html.ActionLink("Button Name", "Index", null, new { @class="classname" }) %>

然后在样式表中创建一个类

a.classname
{
    background: url(../Images/image.gif) no-repeat top left;
     display: block;
     width: 150px;
     height: 150px;
     text-indent: -9999px; /* hides the link text */
}

Late response but you could just keep it simple and apply a CSS class to the htmlAttributes object.

<%= Html.ActionLink("Button Name", "Index", null, new { @class="classname" }) %>

and then create a class in your stylesheet

a.classname
{
    background: url(../Images/image.gif) no-repeat top left;
     display: block;
     width: 150px;
     height: 150px;
     text-indent: -9999px; /* hides the link text */
}
成熟稳重的好男人 2024-07-21 11:18:07

借用帕特里克的答案,我发现我必须这样做:

<button onclick="location.href='@Url.Action("Index", "Users")';return false;">Cancel</button>

避免调用表单的 post 方法。

Borrowing from Patrick's answer, I found that I had to do this:

<button onclick="location.href='@Url.Action("Index", "Users")';return false;">Cancel</button>

to avoid calling the form's post method.

2024-07-21 11:18:07

你可以说我太简单了,但我就是这么做的:

<a href="<%: Url.Action("ActionName", "ControllerName") %>">
    <button>Button Text</button>
</a>

你只需处理超链接的突出显示即可。 我们的用户喜欢它:)

Call me simplistic, but I just do:

<a href="<%: Url.Action("ActionName", "ControllerName") %>">
    <button>Button Text</button>
</a>

And you just take care of the hyperlink highlight. Our users love it :)

半枫 2024-07-21 11:18:07

使用 bootstrap 这是创建显示为动态按钮的控制器操作链接的最短、最简洁的方法:

<a href='@Url.Action("Action", "Controller")' class="btn btn-primary">Click Me</a>

或者使用 Html 助手:

@Html.ActionLink("Click Me", "Action", "Controller", null, new { @class = "btn btn-primary" })

Using bootstrap this is the shortest and cleanest approach to create a link to a controller action that appears as a dynamic button:

<a href='@Url.Action("Action", "Controller")' class="btn btn-primary">Click Me</a>

Or to use Html helpers:

@Html.ActionLink("Click Me", "Action", "Controller", null, new { @class = "btn btn-primary" })
紅太極 2024-07-21 11:18:07

如果您不想使用链接,请使用按钮。 您也可以将图像添加到按钮:

<button type="button" onclick="location.href='@Url.Action("Create", "Company")'" >
   Create New
   <img alt="New" title="New" src="~/Images/Button/plus.png">
</button>

type="button" 执行您的操作而不是提交表单。

if you don't want to use a link, use button. you can add image to button as well:

<button type="button" onclick="location.href='@Url.Action("Create", "Company")'" >
   Create New
   <img alt="New" title="New" src="~/Images/Button/plus.png">
</button>

type="button" performs your action instead of submitting form.

半边脸i 2024-07-21 11:18:07

只是简单地说:

<button onclick="@Url.Action("index", "Family", new {familyid = Model.FamilyID })">Cancel</button>

Just simply :

<button onclick="@Url.Action("index", "Family", new {familyid = Model.FamilyID })">Cancel</button>
╰つ倒转 2024-07-21 11:18:07

答案很晚,但这就是我将 ActionLink 变成按钮的方法。 我们在项目中使用 Bootstrap,因为它很方便。 别介意@T,因为它只是我们使用的翻译器。

@Html.Actionlink("Some_button_text", "ActionMethod", "Controller", "Optional parameter", "html_code_you_want_to_apply_to_the_actionlink");

上面给出了这样的链接,如下图所示:

localhost:XXXXX/Firms/AddAffiliation/F0500

picture Demonstration Button with bootstrap

在我看来:

@using (Html.BeginForm())
{
<div class="section-header">
    <div class="title">
        @T("Admin.Users.Users")
    </div>
    <div class="addAffiliation">
        <p />
        @Html.ActionLink("" + @T("Admin.Users.AddAffiliation"), "AddAffiliation", "Firms", new { id = (string)@WorkContext.CurrentFirm.ExternalId }, new { @class="btn btn-primary" })
    </div>
</div>

}

希望这个帮助某人

A late answer but this is how I make my ActionLink into a button. We're using Bootstrap in our project as it makes it convenient. Never mind the @T since its only an translator we're using.

@Html.Actionlink("Some_button_text", "ActionMethod", "Controller", "Optional parameter", "html_code_you_want_to_apply_to_the_actionlink");

The above gives a link like this and it looks as the picture below:

localhost:XXXXX/Firms/AddAffiliation/F0500

picture demonstrating button with bootstrap

In my view:

@using (Html.BeginForm())
{
<div class="section-header">
    <div class="title">
        @T("Admin.Users.Users")
    </div>
    <div class="addAffiliation">
        <p />
        @Html.ActionLink("" + @T("Admin.Users.AddAffiliation"), "AddAffiliation", "Firms", new { id = (string)@WorkContext.CurrentFirm.ExternalId }, new { @class="btn btn-primary" })
    </div>
</div>

}

Hope this helps somebody

情绪失控 2024-07-21 11:18:07

您无法使用 Html.ActionLink 执行此操作。 您应该使用 Url.RouteUrl 并使用 URL 来构造您想要的元素。

You can't do this with Html.ActionLink. You should use Url.RouteUrl and use the URL to construct the element you want.

标点 2024-07-21 11:18:07

将 Html.ActionLink 变成按钮的简单方法(只要插入了 BootStrap - 您可能已经插入)如下所示:

@Html.ActionLink("Button text", "ActionName", "ControllerName", new { @class = "btn btn-primary" })

A simple way to do make your Html.ActionLink into a button (as long as you have BootStrap plugged in - which you probably have) is like this:

@Html.ActionLink("Button text", "ActionName", "ControllerName", new { @class = "btn btn-primary" })
眼趣 2024-07-21 11:18:07

<button onclick="location.href='@Url.Action("NewCustomer", "Customers")'">Checkout >></button>

晨曦÷微暖 2024-07-21 11:18:07

甚至后来的回复,但我刚刚遇到了类似的问题,最终编写了自己的 图像链接 HtmlHelper 扩展

您可以在我的博客上面的链接中找到它的实现。

只是添加以防有人正在寻找实现。

Even later response, but I just ran into a similar issue and ended up writing my own Image link HtmlHelper extension.

You can find an implementation of it on my blog in the link above.

Just added in case someone is hunting down an implementation.

蓝戈者 2024-07-21 11:18:07
<li><a href="@Url.Action(  "View", "Controller" )"><i class='fa fa-user'></i><span>Users View</span></a></li>

显示带有链接的图标

<li><a href="@Url.Action(  "View", "Controller" )"><i class='fa fa-user'></i><span>Users View</span></a></li>

To display an icon with the link

泛滥成性 2024-07-21 11:18:07

按照 Mehrdad 所说的操作 - 或者使用 HtmlHelper 扩展方法中的 url 帮助器,如 Stephen Walther 描述的 此处 并创建您自己的扩展方法,可用于呈现您的所有链接。

然后,可以很容易地将所有链接呈现为按钮/锚点或任何您喜欢的方式 - 而且最重要的是,当您发现您实际上更喜欢其他制作链接的方式时,您可以稍后改变主意。

Do what Mehrdad says - or use the url helper from an HtmlHelper extension method like Stephen Walther describes here and make your own extension method which can be used to render all of your links.

Then it will be easy to render all links as buttons/anchors or whichever you prefer - and, most importantly, you can change your mind later when you find out that you actually prefer some other way of making your links.

抱猫软卧 2024-07-21 11:18:07

您可以创建自己的扩展方法
看看我的实现

public static class HtmlHelperExtensions
{
    public static MvcHtmlString ActionImage(this HtmlHelper html, string action, object routeValues, string imagePath, string alt, object htmlAttributesForAnchor, object htmlAttributesForImage)
    {
        var url = new UrlHelper(html.ViewContext.RequestContext);

        // build the <img> tag
        var imgBuilder = new TagBuilder("img");
        imgBuilder.MergeAttribute("src", url.Content(imagePath));
        imgBuilder.MergeAttribute("alt", alt);
        imgBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributesForImage));
        string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

        // build the <a> tag
        var anchorBuilder = new TagBuilder("a");
        anchorBuilder.MergeAttribute("href", action != null ? url.Action(action, routeValues) : "#");
        anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
        anchorBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributesForAnchor));

        string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
        return MvcHtmlString.Create(anchorHtml);
    }
}

,然后在您的视图中使用它看看我的调用

 @Html.ActionImage(null, null, "../../Content/img/Button-Delete-icon.png", Resource_en.Delete,
               new{//htmlAttributesForAnchor
                   href = "#",
                   data_toggle = "modal",
                   data_target = "#confirm-delete",
                   data_id = user.ID,
                   data_name = user.Name,
                   data_usertype = user.UserTypeID
               }, new{ style = "margin-top: 24px"}//htmlAttributesForImage
                    )

you can create your own extension method
take look at my implementation

public static class HtmlHelperExtensions
{
    public static MvcHtmlString ActionImage(this HtmlHelper html, string action, object routeValues, string imagePath, string alt, object htmlAttributesForAnchor, object htmlAttributesForImage)
    {
        var url = new UrlHelper(html.ViewContext.RequestContext);

        // build the <img> tag
        var imgBuilder = new TagBuilder("img");
        imgBuilder.MergeAttribute("src", url.Content(imagePath));
        imgBuilder.MergeAttribute("alt", alt);
        imgBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributesForImage));
        string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

        // build the <a> tag
        var anchorBuilder = new TagBuilder("a");
        anchorBuilder.MergeAttribute("href", action != null ? url.Action(action, routeValues) : "#");
        anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
        anchorBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributesForAnchor));

        string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
        return MvcHtmlString.Create(anchorHtml);
    }
}

then use it in your view take look at my call

 @Html.ActionImage(null, null, "../../Content/img/Button-Delete-icon.png", Resource_en.Delete,
               new{//htmlAttributesForAnchor
                   href = "#",
                   data_toggle = "modal",
                   data_target = "#confirm-delete",
                   data_id = user.ID,
                   data_name = user.Name,
                   data_usertype = user.UserTypeID
               }, new{ style = "margin-top: 24px"}//htmlAttributesForImage
                    )
半窗疏影 2024-07-21 11:18:07

对于 Material Design Lite 和 MVC:

<a class="mdl-navigation__link" href='@Url.Action("MyAction", "MyController")'>Link Name</a>

For Material Design Lite and MVC:

<a class="mdl-navigation__link" href='@Url.Action("MyAction", "MyController")'>Link Name</a>
神爱温柔 2024-07-21 11:18:07
@using (Html.BeginForm("DeleteMember", "Member", new { id = Model.MemberID }))
    {
        <input type="submit" value="Delete Member" onclick = "return confirm('Are you sure you want to delete the member?');" />
    }
@using (Html.BeginForm("DeleteMember", "Member", new { id = Model.MemberID }))
    {
        <input type="submit" value="Delete Member" onclick = "return confirm('Are you sure you want to delete the member?');" />
    }
此岸叶落 2024-07-21 11:18:07

关于如何创建显示为图像的链接似乎有很多解决方案,但没有一个使它看起来像一个按钮。

我发现只有一个好方法可以做到这一点。 它有点老套,但它确实有效。

您所要做的就是创建一个按钮和一个单独的操作链接。 使用 css 使操作链接不可见。 当您单击按钮时,它可以触发操作链接的单击事件。

<input type="button" value="Search" onclick="Search()" />
 @Ajax.ActionLink("Search", "ActionName", null, new AjaxOptions {}, new { id = "SearchLink", style="display:none;" })

function Search(){
    $("#SearchLink").click();
 }

每次添加需要看起来像按钮的链接时执行此操作可能会很痛苦,但它确实可以实现所需的结果。

There seems to be lots of solutions on how to created a link that displays as an image, but none that make it appear to be a button.

There is only good way that I have found to do this. Its a little bit hacky, but it works.

What you have to do is create a button and a separate action link. Make the action link invisible using css. When you click on the button, it can fire the click event of the action link.

<input type="button" value="Search" onclick="Search()" />
 @Ajax.ActionLink("Search", "ActionName", null, new AjaxOptions {}, new { id = "SearchLink", style="display:none;" })

function Search(){
    $("#SearchLink").click();
 }

It may be a pain in the butt to do this every time you add a link that needs to look like a button, but it does accomplish the desired result.

夜深人未静 2024-07-21 11:18:07

使用格式

<input type="submit" value="Delete" formaction="@Url.Action("Delete", new { id = Model.Id })" />

use FORMACTION

<input type="submit" value="Delete" formaction="@Url.Action("Delete", new { id = Model.Id })" />
一指流沙 2024-07-21 11:18:07

刚刚找到这个扩展来做到这一点 - 简单而有效。

Just found this extension to do it - simple and effective.

不必你懂 2024-07-21 11:18:07

我这样做的方法是将 actionLink 和图像分开。
将actionlink图像设置为隐藏
然后添加一个 jQuery 触发器调用。 这更多的是一种解决方法。

'<%= Html.ActionLink("Button Name", "Index", null, new { @class="yourclassname" }) %>'
<img id="yourImage" src="myImage.jpg" />

触发示例:

$("#yourImage").click(function () {
  $('.yourclassname').trigger('click');
});

The way I have done it is to have the actionLink and the image seperately.
Set the actionlink image as hidden
and then added a jQuery trigger call. This is more of a workaround.

'<%= Html.ActionLink("Button Name", "Index", null, new { @class="yourclassname" }) %>'
<img id="yourImage" src="myImage.jpg" />

Trigger example:

$("#yourImage").click(function () {
  $('.yourclassname').trigger('click');
});
魄砕の薆 2024-07-21 11:18:07

Url.Action() 将为您提供大多数 Html.ActionLink 重载的裸 URL,但我认为 URL-from-lambda到目前为止,功能只能通过 Html.ActionLink 获得。 希望他们能在某个时候向 Url.Action 添加类似的重载。

Url.Action() will get you the bare URL for most overloads of Html.ActionLink, but I think that the URL-from-lambda functionality is only available through Html.ActionLink so far. Hopefully they'll add a similar overload to Url.Action at some point.

月下客 2024-07-21 11:18:07

这就是我在没有脚本的情况下完成的方法:

@using (Html.BeginForm("Action", "Controller", FormMethod.Get))
{
    <button type="submit" 
            class="btn btn-default" 
            title="Action description">Button Label</button>
}

相同,但带有参数和确认对话框:

@using (Html.BeginForm("Action", "Controller", 
        new { paramName = paramValue }, 
        FormMethod.Get, 
        new { onsubmit = "return confirm('Are you sure?');" }))
{
    <button type="submit" 
            class="btn btn-default" 
            title="Action description">Button Label</button>
}

This is how I did it without scripting:

@using (Html.BeginForm("Action", "Controller", FormMethod.Get))
{
    <button type="submit" 
            class="btn btn-default" 
            title="Action description">Button Label</button>
}

Same, but with parameter and confirmation dialog:

@using (Html.BeginForm("Action", "Controller", 
        new { paramName = paramValue }, 
        FormMethod.Get, 
        new { onsubmit = "return confirm('Are you sure?');" }))
{
    <button type="submit" 
            class="btn btn-default" 
            title="Action description">Button Label</button>
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文