I have a button type that designed with bootstrap classes and I want to do this reusable.
My Edit Button
<a href="#Url.Action("Edit", new {id = item.Id})" class="btn btn-warning btn-sm">
<i class="glyphicon glyphicon-pencil"></i>
</a>
My Delete Button
<a href="#Url.Action("Delete", new {id = item.Id})" class="btn btn-danger btn-sm">
<i class="glyphicon glyphicon-trash"></i>
</a>
How can I do this format as reusable. With partials or with HtmlHelpers? Is there any sample?
As # Stephen suggested you can use both,You can create a HTML Helpers by using the below code
namespace System.Web.Mvc
{
public static class CustomHtmlHelpers
{
public static MvcHtmlString BootStarpDeleteHelper(this HtmlHelper htmlHelper, string action)
{
StringBuilder sb = new StringBuilder();
sb.Append("<a href=" + action + " class='btn btn-danger btn-sm'>");
sb.Append("<i class='glyphicon glyphicon-trash'></i>");
sb.Append("</a>");
return MvcHtmlString.Create(sb.ToString());
}
}
}
in the main view you can call the html helper like this
#Html.BootStarpDeleteHelper("#");
Else you can also create a partial view in the Shared folder and create a new partial view with name _BootStarpDelete
The view look like this
#{
Layout = null;
}
<a href="#Url.Action("Delete", new {id = item.Id})" class="btn btn-danger btn-sm">
<i class="glyphicon glyphicon-trash"></i>
</a>
In the main view you can render like this
#Html.RenderPartial("_BootStarpDelete")
Hope the above explanation will help you.If you want a single html helper for both edit and delete you need to pass classes as parameters.If the same if you want to do the partial view way then you have to pass a model with appropriate value such as action and classes
I have a script which works well.
<button id="sample_editable_1_new" class="btn sbold green">
Add New
<i class="fa fa-plus"></i>
</button>
I would like to change to using the script below.
#Html.ActionLink("Add New", "Create", "Customer", null, new { #class = "btn sbold green", xxx})
How do i add the property?
You could use a CSS class to append the plus character to the link.
.plus-icon:after { content: "\f067"; font-family: 'FontAwesome'; padding-left: 5px; }
Then add the class to your action link
#Html.ActionLink("Add New", "Create", "Customer", null, new { #class = "btn sbold green plus-icon", xxx})
#Html.ActionLink generate <a> tag if you want to use button you should use either js or change your button to a tag.
It's better to generate it with #Url.Action helper if you don't want any js:
<a href='#Url.Action("Create", "Customer")'
id="sample_editable_1_new"
class="btn sbold green">
Add New
<i class="fa fa-plus"></i>
</a>
Html.ActionLink("Create New", "Create", CONTROLLERNAME, null, new { #class= "yourCSSclass"}
Html.ActionLink(link text, action name, controller name, route values object, html attributes object)
Html.ActionLink(
"Create New",
"Create",
CONTROLLERNAME,
null,
new { #class= "yourCSSclass", #style= "width:100px; color: red;" }
)
I am trying to make look #Html.Actionlink as button.
Working Html.Actionlink:
<li class="btn btn-sm"> #Html.ActionLink("Redeem Reward", "GetReward",
"Home", new { id = price.PriceId }, new { #class = "lnkGetReward"})</li>
Currently when I click it looks like as if a link is clicked, apart from the text if we click the button border it doesn't work.
I am also using font awesome classes.
Can I use #Url.Action instead with same id and #class?
Instead of having your button classes on the li apply them directly to the link.
As you are using bootstrap you might want to add btn-default to get the full style of the button.
<li>
#Html.ActionLink("Redeem Reward", "GetReward", "Home",
new { id = price.PriceId },
new { #class = "lnkGetReward btn btn-default btn-sm"})
</li>
However if you are 100% sure you want to use Url.Action your code would look like the following.
<li class="btn btn-sm">
Redeem Reward
</li>
Again I would suggest that you apply the btn btn-sm directly to the link. Possibly with a btn-default.
Edit based on comment:
<li>
<a href="#Url.Action("GetReward", "Home", new { id = price.PriceId })" class="lnkGetReward btn btn-default btn-sm">
<i class="fa fa-mobile"></i> Redeem Reward
</a>
</li>
I have a simple foreach template and inside every element I want an ActionLink but that ActionLink needs to send an Id to edit the element.
The item to be templated:
<div data-bind="template: {
name: 'postsTemplate',
foreach: posts
}">
</div>
The template:
<script id="postsTemplate" type="text/html">
<h2 data-bind="text: Title"></h2>
<p class="post-info">
<p class="post-info" data-bind="text UserName"></p>
<span data-bind="Body"></span>
<p class="post-footer">
#Html.ActionLink("Comments", "IndividualPost", "Post", null, null, "comments", new {id = })
</p>
</p>
</script>
How can I send the actual post Id through the ActionLink? I mean, How I can access to the post's id without using data-bind? (Because it's a helper).
If you would implement your own ActionLink extension along the line of:
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText,
string actionName, string controllerName,
object routeValues, bool noEncode)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var url = urlHelper.Action(actionName, controllerName, routeValues);
if (noEncode) url = Uri.UnescapeDataString(url);
var tagBuilder = new TagBuilder("a");
tagBuilder.MergeAttribute("href", url);
tagBuilder.InnerHtml = linkText;
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
}
Then you could make your template like:
<p class="post-info">
<p class="post-info" data-bind="text UserName"></p>
<span data-bind="Body"></span>
<p class="post-footer">
#Html.ActionLink("Comments (${CommentCount})", "IndividualPost", "Post",
new {id = "${id}"}, true)
</p>
</p>
the serverside html generated would then look like:
<p class="post-info">
<p class="post-info" data-bind="text UserName"></p>
<span data-bind="Body"></span>
<p class="post-footer">
Comments (${CommentCount})
</p>
</p>
which in turn is a perfect template in my opinion.
The reason for an ActionLink extension is the fact that the normal Html.ActionLink encodes your url to /Post/IndividualPost/%24%7Bid%7D which doesn't work for the template
option 1:
- your posts viewmodel is probably coming from the server, it could contain the link.
{
title:'post title',
commentsUrl:'/Indivdualpost/comments/123'
}
on the server
return new post { comment='post title', commentsUrl=Url.Action('Comments','Individualposts', new {id=1234}); }
and then render the comments url in the template:
<a data-bind="attr: {href:commentsUrl}">comments</a>
option 2:
script using a form
<form id="frm" action="#Url.Action("Comments","IndividualPost")>
<input type="hidden" name="id" id="postid"/>
<!-- template stuff -->
</form>
and in the template
<p class="post-footer">
<a data-bind="click:function(){ $('#postid').val(${$id}); $('#frm').submit(); }">comments</a>
</p>
(the click attribute is quite ugly, should be improved using a binding handler or a viewmodel function ( http://www.knockmeout.net/2011/08/simplifying-and-cleaning-up-views-in.html ))
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?
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.
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 */
}
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.
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 :)
Using bootstrap this is the shortest and cleanest approach to create a link to a controller action that appears as a dynamic button:
Click Me
Or to use Html helpers:
#Html.ActionLink("Click Me", "Action", "Controller", new { #class = "btn btn-primary" })
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.
Just simply :
<button onclick="#Url.Action("index", "Family", new {familyid = Model.FamilyID })">Cancel</button>
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
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
You can't do this with Html.ActionLink. You should use Url.RouteUrl and use the URL to construct the element you want.
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" })
<button onclick="location.href='#Url.Action("NewCustomer", "Customers")'">Checkout >></button>
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.
<li><i class='fa fa-user'></i><span>Users View</span></li>
To display an icon with the link
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.
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
)
For Material Design Lite and MVC:
<a class="mdl-navigation__link" href='#Url.Action("MyAction", "MyController")'>Link Name</a>
#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?');" />
}
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.
use FORMACTION
<input type="submit" value="Delete" formaction="#Url.Action("Delete", new { id = Model.Id })" />
Just found this extension to do it - simple and effective.
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');
});
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.
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>
}