问题
I want to create a custom actionlink but I don't know how to do this while fulfilling my needs. I worked with custom htmlhelpers before but this is a bit more tricky for me.
The actionlink
that I want to call needs to be like this:
@Html.CustomActionLink("LinkText", "Area","Controller","TabMenu","Action",routeValues, htmlAttributes)
so an example would be:
@Html.CustomActionLink("Click here","Travel","Trip","Index","Index", new { par1 = "test", par2 = test2, new { @class = "font-color-blue" })`
Which would generate this html:
<a class="font-color-blue" href="/Trip/Travel/Index/Index?par1=test&par2=test2">Click Here</a>
And my route looks like:
context.MapRoute(
"EPloeg_default",
"EPloeg/{controller}/{tabmenu}/{action}/{id}/{actionMethod}",
new { action = "Index", id = UrlParameter.Optional, actionMethod = UrlParameter.Optional }
);
Any ideas how I can make this?
回答1:
How about following code,
@Html.ActionLink("Click here","Trip","Index", new { area= "Travel", tabmenu= "Index"}, new { @class = "font-color-blue" })
EDIT
You can use a extension method like this,
public static MvcHtmlString CustomActionLink(this HtmlHelper htmlHelper, string linkText, string area, string controller, string tabMenu, string action, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)
{
routeValues.Add("area", area);
routeValues.Add("tabMenu", tabMenu);
return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes);
}
回答2:
You can implement custom Action Link extensions, you have to write your own method inside LinkExtensions
class:
namespace TestCustomHelper.Html
{
public static class LinkExtensions
{
public static MvcHtmlString ActionLinkAuthorized(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes, bool showActionLinkAsDisabled)
{
if (htmlHelper.ActionAuthorized(actionName, controllerName))
{
return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes);
}
return MvcHtmlString.Empty;
}
}
and use it in view:
@using TestCustomHelper.Html
@Html.ActionLinkAuthorized("Create New", "Create", new { org = ViewBag.OrgBranchID }, new { @id = "linkCreateEmployee" },true)
NOTE:
I have added one extara bool parameter if you see the last parameter of the method, you can add more according to your need.
i just wrote one overload for it according to my needs, you can write all overloads as Html.ActionLink()
has.
See my tutorial on Creating Custom Html Helper Extensions in asp.net mvc
Also see Official asp.net mvc Creating Custom HTML Helpers
Update
you may want to see my this answer in which custom Action Link I wrote
来源:https://stackoverflow.com/questions/25763232/create-a-custom-actionlink