I need to do with HtmlHelper in Controller, so how i create it in Controller (asp.net mvc 2.0)?
-
See my edit as to how to get it to work in MVC 2.0griegs– griegs2010-01-18 04:39:03 +00:00Commented Jan 18, 2010 at 4:39
-
2What would you want with the HtmlHelper outside of a view?Ajw– Ajw2010-01-18 04:49:36 +00:00Commented Jan 18, 2010 at 4:49
-
1I 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...griegs– griegs2010-01-18 04:54:43 +00:00Commented Jan 18, 2010 at 4:54
Add a comment
|
2 Answers
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();
3 Comments
Eilon
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.
Tobias J
@Eilon for posterity, it looks like System.Web.Mvc.WebFormView does not have a constructor that takes a single string.
Pangamma
Would this cause a memory leak with the text writer?
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();
}
}