Moh*_*mar 26 html.actionlink asp.net-mvc-3 asp.net-mvc-4
我想使用自定义@ Html.ActionLink
我想使用以下代码: -
public static class LinkExtensions
{
public static MvcHtmlString MyActionLink(
this HtmlHelper htmlHelper,
string linkText,
string action,
string controller)
{
var currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
var currentController = mlHelper.ViewContext.RouteData.GetRequiredString("controller");
if (action == currentAction && controller == currentController)
{
var anchor = new TagBuilder("a");
anchor.Attributes["href"] = "#";
anchor.AddCssClass("currentPageCSS");
anchor.SetInnerText(linkText);
return MvcHtmlString.Create(anchor.ToString());
}
return htmlHelper.ActionLink(linkText, action, controller);
}
}
Run Code Online (Sandbox Code Playgroud)
来自Custom ActionLink帮助程序,它知道您所在的页面
但我得到了
System.Web.Mvc.HtmlHelper'不包含'ActionLink'的定义,也没有扩展方法'ActionLink'接受类型'System.Web.Mvc.HtmlHelper'的第一个参数(你是否缺少using指令或装配参考?
Joh*_*ner 16
确保您的web.config中包含扩展类的命名空间.例如:
namespace MyProject.Extensions
{
public static class LinkExtensions
{
//code
}
}
Run Code Online (Sandbox Code Playgroud)
在您的站点Web.config和/或位于"Views"文件夹中的Web.config:
<system.web>
<pages>
<namespaces>
<add namespace="MyProject.Extensions" />
</namespaces>
</pages>
</system.web>
Run Code Online (Sandbox Code Playgroud)
否则,在视图页面顶部包含命名空间的"using"块可以工作,但对于常见的命名空间,我会做上述操作.
ASPX:
<%@ Import namespace="MyProject.Extensions" %>
Run Code Online (Sandbox Code Playgroud)
剃刀:
@using MyProject.Extensions
Run Code Online (Sandbox Code Playgroud)
不要忘记第一个参数只接受string。如果不是,它会向您显示此错误。
确保您在类文件中使用以下内容:
using System.Web.Mvc.Html;
Run Code Online (Sandbox Code Playgroud)
这是必需的,因为HtmlHelper
该类位于System.Web.Mvc
命名空间中,但ActionLink
扩展方法位于System.Web.Mvc.Html
命名空间中.
归档时间: |
|
查看次数: |
73676 次 |
最近记录: |