在的HtmlHelper控制器 [英] HtmlHelper in controller

查看:135
本文介绍了在的HtmlHelper控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个实例的HtmlHelper在我的控制器。

我如何实例化一个?谢谢

这不建:

  VAR H =新的HtmlHelper(新ViewContext(ControllerContext,新WebFormView(OMG),新的ViewDataDictionary(),新TempDataDictionary()),新的ViewPage());

以下是错误的截图

此外,当我看的方法列表 VAR H在,我只看到我的自定义扩展方法,并没有固定的像 ActionLink的。这样一个需要列举为好。 (由sternr解决)

解决方案:


  1. 确保System.Web.Mvc.Html也包括在内。


  2. 下面是code实例化的HtmlHelper。

    System.IO.TextWriter作家=新System.IO.StringWriter();

    VAR HTML =新的HtmlHelper(新ViewContext(ControllerContext,新WebFormView(ControllerContext,妈呀),新的ViewDataDictionary(),新TempDataDictionary(),作家),新的ViewPage());



解决方案

HtmlHelper.ActionLink,大部分找你可能寻找的方法正在申报的扩展方法 System.Web.Mvc.Html 命名空间。

至于使用的HtmlHelper控制器内实例化\\ - 这是一个不好的做法,因为你显然与控制器code组合UI code。什么是你想acheive?

I need a HtmlHelper instance in my controller.

How can I instantiate one? thanks

This does not build:

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

Here is a screenshot of the error

Also, when I look at the list of methods under var h, I only see my custom extension methods and no regular ones like ActionLink. So that one needs to list as well. (solved by sternr)

Solution:

  1. Ensure System.Web.Mvc.Html is included.

  2. Here is the code to instantiate a HtmlHelper.

    System.IO.TextWriter writer = new System.IO.StringWriter();

    var html = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView(ControllerContext, "omg"), new ViewDataDictionary(), new TempDataDictionary(), writer), new ViewPage());

解决方案

HtmlHelper.ActionLink and most of the methods you'r probably looking for are extension methods declared under the System.Web.Mvc.Html namespace.

As for instantiating\using HtmlHelper inside your controller - this is a bad practice as your clearly combine UI code with Controller code. What are you trying to acheive?

这篇关于在的HtmlHelper控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆