Actionlink with text & icon? - asp.net-mvc

I have this link in clean HTML. I want to make it into a MVC ActionLink. But how is that possible. I cant understund, seems there is no easy way. OR?
<li class="active"><i class="icon-home icon-large"></i> Dashboard</li>
Any ideas?

You have several options for doing this.
Option 1:
<li class="active"><i class="icon-home icon-large"></i> Dashboard</li>
Option 2:
Write your own extension method for HtmlHelper, that takes in a String/MvcHtmlString and put it into the link tag, without html encoding it.
public static MvcHtmlString SpecialActionLink(this HtmlHelper html, String action, String controller, String innerHtml) {
TagBuilder tag = new TagBuilder("a");
tag.MergeAttribute("href", new UrlHelper(html.ViewContext.RequestContext).Action(action, controller));
tag.InnerHtml = innerHtml;
return new MvcHtmlString(tag.ToString(TagRenderMode.Normal));
}
(Haven't tested it, but should give you an idea on how to do it.)

<li class="active">
#Html.ActionLink("Dashboard", //Title
"Index", // Action
"Home", // Controller
new { #class = "home-icon"} // htmlAttributes
)
</li>
.home-icon{ /*Some CSS to set the background image (not tested) */
padding:16px;
background:transparent url('path-to-image.png') .... ;
}

You Can't use ActionLink. only way is #url.action
<span>This is a test</span>

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

Insert Glyphicons bootstrap in #Html.ActionLink mvc asp.net

Would enter Glyphicons Boostrap instead of "Edit" in the code below. Could you give me an example to do.
#Html.ActionLink("Edit", "Edit", new { id = Model.id_rod }) |
To bring up the image instead of writing.
If using Bootstrap 3:
<a href="#Url.Action("Edit", new { id = Model.id_rod })">
<i class="glyphicon glyphicon-pencil"></i>
<span class="sr-only">Edit</span>
</a>
Note the use of sr-only will allow users of screen readers and search engines to know what the link is for.
I made helper for easier re-use
Helper Method Extension class
namespace Extensions {
public static class HtmlExtensions {
public static MvcHtmlString FALink(this HtmlHelper htmlHelper, string action, string controller, string link_text, string fa_class, string btn_css_classes = "", string button_id = "", object route_values = null) {
// declare the span for the glyphicon
TagBuilder span = new TagBuilder("span");
span.AddCssClass($"fa fa-{fa_class}");
span.MergeAttribute("aria-hidden", "true");
// declare the anchor tag
TagBuilder anchor = new TagBuilder("a");
// Add the href attribute to the <a> element
if (string.IsNullOrEmpty(controller) || string.IsNullOrEmpty(action))
anchor.MergeAttribute("href", "#");
else
anchor.MergeAttribute("href", new UrlHelper(HttpContext.Current.Request.RequestContext).Action(action, controller, route_values));
// Add the <span> element and the text to the <a> element
anchor.InnerHtml = $"{span} {link_text}";
anchor.AddCssClass(btn_css_classes);
anchor.GenerateId(button_id);
// Create the helper
return MvcHtmlString.Create(anchor.ToString(TagRenderMode.Normal));
}
}
}
Make sure you include the namespace in the View so method is available
Example usage in Razor View (Leave area empty string if your not using areas)
#Html.FALink("Index", "ControllerNameHere", "Back to List", "th-list", "btn btn-info", "btn_back_to_list", new {area=""})
While I use Font Awesome you could easily replace fa with glyphicon class to use the bootstrap glyphicons.
If no controller or Action is passed in, it uses # as the link location so it will play nice with drop down interaction

passing html attributes to Html.Actionlink helper function

i want to know that how to pass html attributes to #Html.ActionLink helper function
i want to do like that
<a class="accordion-toggle" data-toggle="collapse" data-parent="#leftMenu" href="/Admin/UserManagment">
<i class="icon-user"></i>User Managment
</a>
how to pass that italic html attribute
You could use #Url.Action() as an alternative.
In this case your code would look like this:
<a class="accordion-toggle" data-toggle="collapse" data-parent="#leftMenu"
href="#Url.Action("UserManagment", "Admin")">
<i class="icon-user"></i>User Managment
</a>
Edit:
Out of interest I did a bit of research and found this answer. Which explains it isn't possible to use the Html.ActionLink for this purpose:
The Html.ActionLink helper HTML encodes the link text which prevents
you from embedding HTML in the link text.
There is no way to wrap html code inside the anchor tag using #Html.ActionLink
You can use #Url.Action
<a href="#Url.Action("UserManagment", "Admin")" ...>
<i class="icon-user"></i>User Managment
</a>
Or create an extension method:
public static IHtmlString MyActionLink(this HtmlHelper helper,
string value,
Dictionary<string, string> attributes,
string innerHtml)
{
var aBuilder = new TagBuilder("a");
foreach (var attr in attributes)
{
aBuilder.MergeAttribute(attr.Key, attr.Value);
}
aBuilder.InnerHtml += innerHtml + value;
return new HtmlString(aBuilder.ToString(TagRenderMode.Normal));
}
And use it in your views like this
#{
var attributes = new Dictionary<string, string>
{
{ "data-toggle", "collapse" },
{ "data-parent", "#leftMenu" },
{ "href", Url.Action("UserManagement", "Admin") }
};
var innerHtml = "<i class='icon-user'></i>";
}
#Html.MyActionLink("User Managment", attributes, innerHtml)

Providing ID in ActionLink() or RouteLink()?

I'm new to MVC and would like to add a link to something like ~/Destinations/35, where it would refer to the Index view of the Destinations controller, and 35 is the ID of the destination to be displayed.
Neither ActionLink() or RouteLink() appear to allow me to create a link such as this.
Also, I tried something like this:
<table>
#foreach (var d in ViewBag.Results)
{
<tr>
<td>
#Html.ActionLink(
String.Format("<b>{0}</b>", #Html.Encode(d.Title)),
"Details", "Destinations")
</td>
</tr>
}
</table>
But I get the following error on the ActionLink line, which I don't understand.
'System.Web.Mvc.HtmlHelper' has no applicable method named 'ActionLink' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
Can someone help me create this link?
The first problem with your code is that you are trying to use HTML in the link text (the <b> tags) which is not possible because by design it always HTML encodes.
So assuming you didn't want HTML in the link you could do this:
#Html.ActionLink(d.Title, "Details", "Destinations", new { id = "35" }, null)
And assuming you need HTML inside the anchor you have a couple of possibilities:
Write a custom ActionLink helper which won't HTML encode the text (recommended) and then use like this:
#Html.MyBoldedActionLink(d.Title, "Details", "Destinations", new { id = "35" }, null)
Something along the lines:
<a href="#Url.Action("Details", "Destinations", new { id = "35" })">
<b>#d.Title</b>
</a>
and since I recommend the first approach here's a sample implementation of the custom helper:
public static class HtmlExtensions
{
public static IHtmlString MyBoldedActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
object routeValues,
object htmlAttributes
)
{
var anchor = new TagBuilder("a");
anchor.InnerHtml = string.Format("<b>{0}</b>", htmlHelper.Encode(linkText));
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
anchor.Attributes["href"] = urlHelper.Action(actionName, controllerName, routeValues);
anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
return new HtmlString(anchor.ToString());
}
}

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