我需要在Controller中使用HtmlHelper,所以我如何在Controller(asp.net mvc 2.0)中创建它?
答案 0 :(得分:8)
这是你想要的吗?
Using HtmlHelper in a Controller
修改强>
使用此功能;
System.IO.TextWriter writer = new System.IO.StringWriter();
var h = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView("omg"), new ViewDataDictionary(), new TempDataDictionary(), writer), new ViewPage());
string g = h.TextBox("myname").ToString();
答案 1 :(得分:7)
你可以使用这样的方法:
public static HtmlHelper GetHtmlHelper(this Controller controller)
{
var viewContext = new ViewContext(controller.ControllerContext, new FakeView(), controller.ViewData, controller.TempData, TextWriter.Null);
return new HtmlHelper(viewContext, new ViewPage());
}
public class FakeView : IView
{
public void Render(ViewContext viewContext, TextWriter writer)
{
throw new NotSupportedException();
}
}