tags:

views:

1608

answers:

4

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.

Thanks in advance!

+5  A: 

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...

Mauricio Scheffer
A: 

There is a tutorial at http://www.asp.net/learn/mvc/tutorial-09-cs.aspx and there are more out there I am sure :).

Morph
Good tutorial but doesn't handle calling HtmlHelper from a controller, which is the subject of this question...
Mauricio Scheffer
+4  A: 

The HtmlHelper is part of the View mechanism by design and should be considered separate to the Controller and Model parts of MVC. I am not sure why you would want to generate controls inside the controller as it's role is to deliver the Data to the view for rendering.

I am not saying that you cannot achieve it, but for good design it would be better.

Can you explain what you are trying to achieve and then we could look at doing it in an "MVC way"?

Richard
I was using it as a way to generate the control's html based on a user selection in an ajax form. Trying to get the same concept as Rails RJS forms. Although the provided solution did work, I agree that this is not the cleanest solution and I will probably end up making it all client side after all.
Gil
A: 

I would like to do this so I can write a custom helper that builds a label tag with the "for" attribute matching a text box (for example) and return all of them together in one go. I'd like to call the existing TextBox helper instead of rewriting it.

Then I could call Html.TextBoxWithLabel("this is a text box", "textyMcBox") and have it spit out:

<label for="textyMcBox">this is a text box</label> <input id="textyMcBox" name="textyMcBox" type="text" value="" />
Idiot