3

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

3
  • See my edit as to how to get it to work in MVC 2.0 Commented Jan 18, 2010 at 4:39
  • 2
    What would you want with the HtmlHelper outside of a view? Commented Jan 18, 2010 at 4:49
  • 1
    I suspect he's trying to construct controls that are passed back to the view. Perhaps in a jQuery post back. I'd prefer to have a partial view which i can render from a view or send back from a jQuery post, but yeah... Commented Jan 18, 2010 at 4:54

2 Answers 2

9

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Are you saying that it doesn't work? These types have changed only minimally between ASP.NET MVC 1.0 and ASP.NET MVC 2. If it doesn't work then let us know what doesn't work.
@Eilon for posterity, it looks like System.Web.Mvc.WebFormView does not have a constructor that takes a single string.
Would this cause a memory leak with the text writer?
7

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.