Fluent interface for rendering HTML

前端 未结 4 1362
不思量自难忘°
不思量自难忘° 2020-12-30 09:21

Rendering HTML with the HtmlTextWriter isn\'t incredibly intuitive in my opinion, but if you\'re implementing web controls in web forms it\'s what you have to work with. I t

4条回答
  •  攒了一身酷
    2020-12-30 09:53

    If you need to do lots of this kind of stuff have you considered some sort of template engine like NHaml?

    In Ruby/Markaby this would look so much prettier.

        div :class=>"someClass someOtherClass" do 
            h1 "Lorem"
            select :id => "fooSelect", :name => "fooSelect", :class => "selectClass" do 
               option :title=>"selects the number 1", :value => 1 { "1" } 
               option :title=>"selects the number 2", :value => 2 { "2" } 
               option :title=>"selects the number 3", :value => 3 { "3" } 
            end
        end
    

    You can port a similar approach to .Net

        using(var d = HtmlTextWriter.Div.Class("hello"))
        {
            d.H1.InnerText("Lorem"); 
            using(var s = d.Select.Id("fooSelect").Name("fooSelect").Class("fooClass"))
            {
               s.Option.Title("select the number 1").Value("1").InnerText("1"); 
            }
        } 
    

    I think it reads quite will and supports nesting.

    EDIT I stole the using from Konrad cause it reads much better.

    I have the following issues with the original proposal

    1. You must remember to call EndTag otherwise your HTML goes Foobar.
    2. Your namspace is too polluted HtmlTextWriterTag is repeated a ton of times and its hard to decipher the content from the overhead.

    My suggested approach is potentially slightly less efficient, but I think it addresses these concerns and would be very easy to use.

提交回复
热议问题