0

我很好奇如何调用LinkExtensions.ActionLink Method (HtmlHelper, String, String)HtmlHelper.ActionLink()中描述的Method以下是我的Controller,在一个空的 MVC 项目中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace TempMVC.Controllers
{
    public class DataController : Controller
    {
       public ActionResult Index()
       {
           HtmlHelper.GenerateLink(
                                   RequestContext requestContext, 
                                   RouteCollection routeCollection, 
                                   string linkText, 
                                   string routeName, 
                                   string actionName, 
                                   string controllerName, 
                                   RouteValueDictionary routeValues, 
                                   IDictionary<string, object> htmlAttributes
           ); //OK
           HtmlHelper.GenerateRouteLink(
                                       RequestContext requestContext, 
                                       RouteCollection routeCollection, 
                                       string linkText, 
                                       string routeName, 
                                       RouteValueDictionary routeValues, 
                                       IDictionary<string, object> htmlAttributes
           ); //OK
           HtmlHelper.ActionLink(string linkText, string actionName); //Error
           return View();
       }
   }
}

虽然我可以使用HtmlHelper.GenerateLink()HtmlHelper.GenerateRouteLink()方法,但当我尝试使用 HtmlHelper.ActionLink() 时出现以下错误:

The type name 'ActionLink' does not exist in the type 'System.Web.Mvc.HtmlHelper'

请注意,我已System.Web.Mvc.Html在顶部声明,并且我看到它在我的Web.config文件中列出。

我可以在控制器中使用 HtmlHelper.ActionLink()方法吗?

4

2 回答 2

3

.ActionLink是需要HtmlHelper对象的扩展方法。所以你可以创建这个对象并使用.ActionLink方法:

var h = new HtmlHelper(
    new ViewContext(
        ControllerContext, 
        new WebFormView("name"), 
        new ViewDataDictionary(), 
        new TempDataDictionary()), 
        new ViewPage());

var link = h.ActionLink("LinkText", "Action"); // type of 'link' is MvcHtmlString
于 2013-07-01T19:06:48.137 回答
2

HTML 助手用于视图,而不是控制器。控制器仅将数据传递给视图。然后视图使用 HTML 帮助器为数据生成 UI。

于 2013-07-01T19:06:58.707 回答