Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using HtmlHelper in a Controller

Tags:

asp.net-mvc

Is it possible to use HtmlHelper in a controller, for-example to get the TextBox(...) method? not that I can't write the html that it generates myself, but I just want to understand how this works so I can create the best solution.

like image 653
Gil Avatar asked Mar 07 '09 03:03

Gil


2 Answers

Here's an example adapted from this:

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

Note that this is a hack, it can be done but I don't think there's any good reason to do this...

like image 168
Mauricio Scheffer Avatar answered Oct 29 '22 15:10

Mauricio Scheffer


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 InvalidOperationException();
    }
}
like image 42
Vitaliy Ulantikov Avatar answered Oct 29 '22 16:10

Vitaliy Ulantikov