Create HtmlHelper instance in Controller

前端 未结 2 1183
再見小時候
再見小時候 2021-01-20 18:05

I need to do with HtmlHelper in Controller, so how i create it in Controller (asp.net mvc 2.0)?

相关标签:
2条回答
  • 2021-01-20 18:49

    You can use method like this:

    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();
     }
    }
    
    0 讨论(0)
  • 2021-01-20 18:59

    Is this what you want?

    Using HtmlHelper in a Controller

    EDIT

    Use this;

    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();
    
    0 讨论(0)
提交回复
热议问题