0

my problem is the following I have an instance of a class and a HtmlTextWriter. Now i want to generate the Editor like in the View. The HtmlHelper is present and the methods Editor, TextBox ... too.

public class Class
{
    public string Test { get; set; }
}

HtmlTextWriter writer = new HtmlTextWriter(new StringWriter());
Class a = new Class(); // 
a.Test = "Lorem ipsum";

how can i do this to get a TextBox and all the goodness of Validations (DataAnnotations) ?

writer.Write(HtmlHelper.Editor(x => ....).ToString());

Have a nice day !

dknaack
  • 60,192
  • 27
  • 155
  • 202

2 Answers2

0

This is Probably not the direct answer to your question. However, you can take a slightly different approach and put everything you want in a view and then render that view as a string. Look at this question. it describes how you can render view to a string.

Community
  • 1
  • 1
Muhammad Adeel Zahid
  • 17,474
  • 14
  • 90
  • 155
0

To get the DataAnnotations validation (using unobtrusive JS) you need a FormContext, which is created when you use the BeginForm helper.

Linkgoron
  • 4,866
  • 2
  • 26
  • 26
  • This is not true. You can manually set the FormContext if you need it `if (Html.ViewContext.FormContext == null) { Html.ViewContext.FormContext = new FormContext(); }` – archil Mar 31 '11 at 09:33
  • @archil What I said *IS* true. I said that one is created when you use the BeginForm helper. How is it not true? I didn't think of telling him to set one himself, and I'll tell you the truth I'm not sure that it's a very smart thing to do. – Linkgoron Mar 31 '11 at 09:42
  • Sorry, you were right about the thing that it's created when BeginForm is executed. Creating FormContext manually is useful when there's the need to load partial view from server via ajax call and you want to insert response into exsiting form that's created on client. In this case, if you don't set FormContext manually, validations wont attach to inputs – archil Mar 31 '11 at 09:53
  • @archil yes, the FormContext is kind of annoying, however the problems I have with setting the FormContext yourself is that it's an implementation detail. I'd almost consider it a hack. It *does* work, however, it's not very clear why it works unless you actually look at the source. IMO, it's clearer that validation only works in a Form scope (when you use 'using', or just BeginForm) it's also easier to understand... I also think that it's more future proof for vNexts. – Linkgoron Mar 31 '11 at 10:03