在ASP的最新(RC1)版本中。NET MVC,我怎么得到Html。ActionLink渲染为按钮或图像而不是链接?
当前回答
URL . action()将为您提供大多数Html重载的纯URL。ActionLink,但我认为URL-from-lambda功能只能通过Html使用。ActionLink到目前为止。希望他们会给Url添加类似的重载。在某种程度上采取行动。
其他回答
你不能用Html.ActionLink这样做。你应该使用Url。RouteUrl并使用该URL来构造所需的元素。
按照Mehrdad说的去做——或者像Stephen Walther在这里描述的那样,使用HtmlHelper扩展方法中的url helper,并创建自己的扩展方法,可以用来呈现所有的链接。
然后它将很容易渲染所有链接作为按钮/锚或任何你喜欢的-而且,最重要的是,你可以改变你的想法,当你发现你实际上更喜欢一些其他的方式制作你的链接。
使用bootstrap,这是创建控制器动作链接的最短和最干净的方法,该控制器动作以动态按钮的形式出现:
<a href='@Url.Action("Action", "Controller")' class="btn btn-primary">Click Me</a>
或者使用Html helper:
@Html.ActionLink("Click Me", "Action", "Controller", new { @class = "btn btn-primary" })
您可以创建自己的扩展方法 看看我的实现
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
)
一个简单的方法做你的Html。ActionLink变成一个按钮(只要你插入了BootStrap -你可能有)是这样的:
@Html.ActionLink("Button text", "ActionName", "ControllerName", new { @class = "btn btn-primary" })
推荐文章
- 把内容放在HttpResponseMessage对象?
- asp.net MVC中的@RenderSection是什么
- 在哪里放置AutoMapper.CreateMaps?
- 我如何提高ASP。NET MVC应用程序性能?
- 如何在剃刀视图上引用.css文件?
- 获取“JSON请求太大,无法反序列化”
- 存储库和服务层的区别?
- 在ASP中实现请求节流的最佳方法。净MVC吗?
- 如何添加ID属性Html.BeginForm()在asp.net mvc?
- 什么是MvcHtmlString,什么时候我应该使用它?
- 生成错误:必须向系统添加引用。运行时
- Visual Studio 2012 Web Publish不复制文件
- 在ASP中使用jQuery渲染局部视图。NET MVC
- 如何返回一个文件(FileContentResult)在ASP。净WebAPI
- Java Server Faces 2.0的主要缺点是什么?