Image button in ActionLink MVC - asp.net-mvc

How to put image instead text in ActionLink button:
#Html.ActionLink("Edit-link", "Edit", new { id=use.userID })
So how to change text "Edit-link" to image?
Thanks for any idea.

do like this:
<a href="#Url.Action("Edit")" id="#use.userID">
<img src="#Url.Content("~/images/someimage.png")" />
</a>
or pass both action and controller name by using other override:
<a href="#Url.Action("Edit","Controller")" id="#use.userID">
<img src="#Url.Content("~/images/someimage.png")" />
</a>
UPDATE:
You can also create a custom Html Helper, and can reuse it in any View in application:
namespace MyApplication.Helpers
{
public static class CustomHtmlHelepers
{
public static IHtmlString ImageActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, object routeValues, object htmlAttributes,string imageSrc)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var img = new TagBuilder("img");
img.Attributes.Add("src", VirtualPathUtility.ToAbsolute(imageSrc));
var anchor = new TagBuilder("a") { InnerHtml = img.ToString(TagRenderMode.SelfClosing) };
anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
return MvcHtmlString.Create(anchor.ToString());
}
}
}
and use it in View:
#using MyApplication.Helpers;
#Html.ImageActionLink("LinkText","ActionName","ControllerName",null,null,"~/images/untitled.png")
Output HTML:
<a href="/ControllerName/ActionName">
<img src="/images/untitled.png">
</a>

Try this code :
#Html.Raw(#Html.ActionLink("Edit-link","Edit", new { id=use.userID }).ToHtmlString().Replace("Edit-link", "<img src=\"/Contents/img/logo.png\" ... />"))
or

<a href="#Url.Action("Edit Link","Edit",new {id = item.EId })">
<img src="#Url.Content("~/img/iconfinder_new-24_103173.png")" style="height:20px;width:20px;color:blue" title="Edit" />
</a>
Try this code. It will add an image linked to the Edit() action with the id set.

Related

Razor Html Helpers Actionlink [duplicate]

How can I do something similar to Html.ActionLink() except place the generated link around an Image instead of just spitting out the link?
Razor (View Engine):
<a href="#Url.Action("ActionName", "ControllerName")">
<img src="#Url.Content("~/Content/img/imgname.jpg")" />
</a>
ASPX (View Engine):
<a href="<%= Url.Action("ActionName", "ControllerName") %>">
<img src="<%= Url.Content("~/Content/img/imgname.jpg") %>" />
</a>
Obviously, if you do this more than once, write a helper for it. And fill in the other attributes of img/a. But this should give you the general idea.
Try something like this:
public static string ActionLinkWithImage(this HtmlHelper html, string imgSrc, string actionName)
{
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
string imgUrl = urlHelper.Content(imgSrc);
TagBuilder imgTagBuilder = new TagBuilder("img");
imgTagBuilder.MergeAttribute("src", imgUrl);
string img = imgTagBuilder.ToString(TagRenderMode.SelfClosing);
string url = UrlHelper.Action(actionName);
TagBuilder tagBuilder = new TagBuilder("a") {
InnerHtml = img
};
tagBuilder.MergeAttribute("href", url);
return tagBuilder.ToString(TagRenderMode.Normal);
}
Hope this helps
The first answer given by #Craig Stuntz is absolutely perfect but my concern is about if what will you do if you have Ajax.ActionLink instead of Html.ActionLink. Here I will explain easy solutions for both methods. You can do as the following for Html.ActonLink:
#Html.Raw(#Html.ActionLink("[replacetext]", "Index", "Home").ToHtmlString().Replace("[replacetext]", "<img src=\"/Contents/img/logo.png\" ... />"))
same concept can be applied for Ajax.ActionLink
#Html.Raw(#Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/Contents/img/logo.png\" … />"))
so this will be easy for you.
Edit:
ActionLink Image with Style Sheet or Class Name
With Style sheet
#Html.Raw(#Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/assets/img/logo.png\" style=\"width:10%\" ... />"))
With Class Name
<style>
.imgClass {
width:20%
}
#Html.Raw(#Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/assets/img/logo.png\" class=\"imgClass\" ... />"))
For more reference regarding ActionLink around Image visit ActionLink around Image in Asp.net MVC
more easy...
change your code by:
<p class="site-title">#Html.ActionLink(" ", "Index", "Home",
new
{
style = "background: url('" + Url.Content("~/images/logo.png") + "') no-repeat center right; display:block; height:50px;width:50px;"
})</p>
You can use url.content:
#Url.Content("~/images/img/slide.png")
this return relative path
You can create htmlhelper which can return image with link...
As parameters you will pass to htmlhelper values like image path and link and in htmlhelper you will use StringBuilder to format html of that linked image properly...
cheers

ASP.NET Actionlink with glyphicon and text with different font

I want to present a button with #Html.ActionLink but i need to have my application font in the text.
With this code:
<span>
#Html.ActionLink(" Create New", "Create", null, new { #class = "btn btn-warning glyphicon glyphicon-plus-sign" })
</span>
I get my button but the Create New text appears with the glyphicon font-family.
Putting the glyphicon classes in the span doesn't change anything
You should not add the glyphicon class to the a-tag.
From the Bootstrap website:
Don't mix with other components
Icon classes cannot be directly combined with other components. They should not be used along with other classes on the same element. Instead, add a nested <span> and apply the icon classes to the <span>.
Only for use on empty elements
Icon classes should only be used on elements that contain no text content and have no child elements.
In other words the correct HTML for this to work the way you want would be: test <span class="glyphicon glyphicon-plus-sign"></span>
This makes the Html.ActionLink helper unsuitable. Instead you could use something like:
<a href="#Url.Action("Action", "Controller")" class="btn btn-warning">
link text
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
</a>
This works for me in MVC 5:
#Html.ActionLink(" ", "EditResources", "NicheSites", new { ViewBag.dbc, item.locale, ViewBag.domainId, domainName = ViewBag.domaiName }, new {#class= "glyphicon glyphicon-edit" })
The first parameter cannot be empty or null or it will blow.
It might be better to just write out the HTML rather than try to make it work with HtmlHelper.ActionLink...
<span>
<a href="#Url.Action("Create")" class="btn btn-warning">
<span class="glyphicon glyphicon-plus-sign"></span>
Create New
</a>
</span>
Here's mine. Inspired by Andrey Burykin
public static class BensHtmlHelpers
{
public static MvcHtmlString IconLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, String iconName, object htmlAttributes = null)
{
var linkMarkup = htmlHelper.ActionLink(linkText, actionName, routeValues, htmlAttributes).ToHtmlString();
var iconMarkup = String.Format("<span class=\"{0}\" aria-hidden=\"true\"></span>", iconName);
return new MvcHtmlString(linkMarkup.Insert(linkMarkup.IndexOf(#"</a>"), iconMarkup));
}
}
I should go with the approach of #Url.Action instead of #Html.ActionLink, se example code below:
<span>
<span class="glyphicon glyphicon-plus-sign"></span> Create New
</span>
You can use simple extension:
private static readonly String SPAN_FORMAT = "<span class=\"{0}\" aria-hidden=\"true\"></span>";
private static readonly String A_END = "</a>";
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, String iconName, object htmlAttributes = null)
{
var linkMarkup = htmlHelper.ActionLink(linkText, actionName, routeValues, htmlAttributes).ToHtmlString();
if (!linkMarkup.EndsWith(A_END))
throw new ArgumentException();
var iconMarkup = String.Format(SPAN_FORMAT, iconName);
return new MvcHtmlString(linkMarkup.Insert(linkMarkup.Length - A_END.Length, iconMarkup));
}
Usage:
Html.ActionLink(" ", "DeleteChart", new { Id = _.Id }, "glyphicon glyphicon-trash")
Try it!
#Html.ActionLink(" Cerrar sesión", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" , #class = "glyphicon glyphicon-log-in" })
Let's have a try on this. Let me know if it is working .Thanks
<style>
span.super a
{
font: (your application font) !important;
}
</style>
<span class="super">
#Html.ActionLink(" Create New", "Create", null, new { #class = "btn btn-warning glyphicon glyphicon-plus-sign" })
</span>
How about using Html.BeginForm with a FormMethod.Get / FormMethod.Post
#using (Html.BeginForm("Action", "Controller", new { Area = "" },
FormMethod.Get, htmlAttributes: new { title = "SomeTitle" }))
{
<button type="submit" class="btn-link" role="menuitem">
<i class="glyphicon glyphicon-plus-sign"></i>Create New</button>
}
Try this. Worked for me.
<button class="btn btn-primary"><i class ="fa fa-plus">#Html.ActionLink(" ", "Create", "Home")</i></button>

How to work with Action Link when using CSS

<li class="rtsLI" id="Summary"><span class="rtsTxt">Test</span></li>
Above I am replacing with following actionlink:
<li class="rtsLI" >#Html.ActionLink("test1", "Index", new { Area = "Area1", Controller = "controller1" }, new { #class = "rtsLink rtsTxt"})</li> "
At first css is working fine. But when using Actionlink, css not working. Thanks
The standard ActionLink helper always HTML encodes the link text. This means that you cannot use it if you want to render HTML inside. You have 3 possibilities:
Modify your CSS so that you don't need a span inside the link and so that the rtsTxt class could directly be applied to the link
Write a custom ActionLink helper that doesn't HTML encode the text and which would allow you to generate the same markup:
public static class ActionLinkExtensions
{
public static IHtmlString ActionLinkUnencoded(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
object routeValues,
object htmlAttributes
)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var link = new TagBuilder("a");
link.MergeAttributes(new RouteValueDictionary(htmlAttributes));
link.Attributes["href"] = urlHelper.Action(actionName, routeValues);
link.InnerHtml = linkText;
return new HtmlString(link.ToString());
}
}
and then:
<li>
#Html.ActionLinkUnencoded(
"<span class=\"rtsTxt\">User Security</span>",
"index",
new { area = "Tools", controller = "UserSecurity" },
new { #class = "rtsLink" }
)
</li>
Use the Url.Action helper:
<li class="rtsLI">
<a href="#Url.Action("index", new { area = "Tools", controller = "UserSecurity" })" class="rtsLink">
<span class="rtsTxt">User Security</span>
</a>
</li>
Best option will be to use #Url.Action extension method
<li class="rtsLI" id="Summary"><span class="rtsTxt">User Security</span></li>
Write code this way:
<li class="rtsLI" >#Html.ActionLink("<span class='rtsTxt'>User Security</span>", "Index", new { Area = "Tools", Controller = "UserSecurity" }, new { #class = "rtsLink"})</li>`

Convert HREF to RouteLink

It seems to be simple, but I can't get anything to work. This code was generated by my template generator and needs to be changed.
<li><a href="../Home/Contact" class="active"><span class="l"></span><span class="r">
</span><span class="t">Nous contacter</span></a> </li>
My best bet up to now is:
<li><span class="l"></span><span class="r"></span>
#Html.RouteLink("Contact", new { Controller = "Home", Action = "Contact" }, new { #class = "t" })</li>
But it doesn't do anything.
Just to make sur that my question is clear: The link works in both cases, that's fine. The formating doesn't work. That's my issue here.
The second will generate:
<li>
<span class="l"></span>
<span class="r"></span>
<a class="t" href="/Home/Contact">Contact</a>
</li>
which is different than what you had in the first place which might explain the formatting problems:
<li>
<a href="../Home/Contact" class="active">
<span class="l"></span>
<span class="r"></span>
<span class="t">Nous contacter</span>
</a>
</li>
The problem with Html helpers such as Html.ActionLink and RouteLink is that they by always Html encode the text, so you cannot use HTML as text. So one possibility is the following:
<li>
<a href="#Url.RouteUrl("Contact", new { controller = "home", action = "contact" })" class="active">
<span class="l"></span>
<span class="r"></span>
<span class="t">Nous contacter</span>
</a>
</li>
Another possibility if you have lots of those to generate is to write a custom Html helper that will do the job for you:
public static class HtmlExtensions
{
public static IHtmlString MyLink(
this HtmlHelper htmlHelper,
string linkText,
string routeName,
object routeValues
)
{
var spans = string.Format(
"<span class=\"l\"></span><span class=\"r\"></span><span class=\"t\">{0}</span>",
htmlHelper.Encode(linkText)
);
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var url = urlHelper.RouteUrl(routeName, routeValues);
var anchor = new TagBuilder("a");
var rvd = new RouteValueDictionary(routeValues);
var rd = htmlHelper.ViewContext.RouteData;
var currentAction = rd.GetRequiredString("action");
var currentController = rd.GetRequiredString("controller");
var controller = rvd["controller"] as string;
var action = rvd["action"] as string;
if (string.Equals(controller, currentController, StringComparison.OrdinalIgnoreCase) &&
string.Equals(action, currentAction, StringComparison.OrdinalIgnoreCase))
{
anchor.AddCssClass("active");
}
anchor.Attributes["href"] = url;
anchor.InnerHtml = spans;
return new HtmlString(anchor.ToString());
}
}
and then:
<li>
#Html.MyLink("Nous contacter", "Contact", new { controller = "home", action = "contact" })
</li>
Just use something like this:
#Url.Action("Index", "Home")

Make an Html.ActionLink around an Image in ASP.NET MVC?

How can I do something similar to Html.ActionLink() except place the generated link around an Image instead of just spitting out the link?
Razor (View Engine):
<a href="#Url.Action("ActionName", "ControllerName")">
<img src="#Url.Content("~/Content/img/imgname.jpg")" />
</a>
ASPX (View Engine):
<a href="<%= Url.Action("ActionName", "ControllerName") %>">
<img src="<%= Url.Content("~/Content/img/imgname.jpg") %>" />
</a>
Obviously, if you do this more than once, write a helper for it. And fill in the other attributes of img/a. But this should give you the general idea.
Try something like this:
public static string ActionLinkWithImage(this HtmlHelper html, string imgSrc, string actionName)
{
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
string imgUrl = urlHelper.Content(imgSrc);
TagBuilder imgTagBuilder = new TagBuilder("img");
imgTagBuilder.MergeAttribute("src", imgUrl);
string img = imgTagBuilder.ToString(TagRenderMode.SelfClosing);
string url = UrlHelper.Action(actionName);
TagBuilder tagBuilder = new TagBuilder("a") {
InnerHtml = img
};
tagBuilder.MergeAttribute("href", url);
return tagBuilder.ToString(TagRenderMode.Normal);
}
Hope this helps
The first answer given by #Craig Stuntz is absolutely perfect but my concern is about if what will you do if you have Ajax.ActionLink instead of Html.ActionLink. Here I will explain easy solutions for both methods. You can do as the following for Html.ActonLink:
#Html.Raw(#Html.ActionLink("[replacetext]", "Index", "Home").ToHtmlString().Replace("[replacetext]", "<img src=\"/Contents/img/logo.png\" ... />"))
same concept can be applied for Ajax.ActionLink
#Html.Raw(#Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/Contents/img/logo.png\" … />"))
so this will be easy for you.
Edit:
ActionLink Image with Style Sheet or Class Name
With Style sheet
#Html.Raw(#Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/assets/img/logo.png\" style=\"width:10%\" ... />"))
With Class Name
<style>
.imgClass {
width:20%
}
#Html.Raw(#Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/assets/img/logo.png\" class=\"imgClass\" ... />"))
For more reference regarding ActionLink around Image visit ActionLink around Image in Asp.net MVC
more easy...
change your code by:
<p class="site-title">#Html.ActionLink(" ", "Index", "Home",
new
{
style = "background: url('" + Url.Content("~/images/logo.png") + "') no-repeat center right; display:block; height:50px;width:50px;"
})</p>
You can use url.content:
#Url.Content("~/images/img/slide.png")
this return relative path
You can create htmlhelper which can return image with link...
As parameters you will pass to htmlhelper values like image path and link and in htmlhelper you will use StringBuilder to format html of that linked image properly...
cheers

Resources