complez
complez

Reputation: 8352

Create HtmlHelper instance in Controller

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

Upvotes: 3

Views: 12241

Answers (2)

Vitaliy Ulantikov
Vitaliy Ulantikov

Reputation: 10534

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();
 }
}

Upvotes: 7

griegs
griegs

Reputation: 22770

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();

Upvotes: 9

Related Questions