Using HtmlTextWriter in ASP.NET MVC

I am porting some old code where HtmlTextWriterit is widely used to render interface elements.

I am porting code to use ASP.NET MVC 1.0. As far as I know, I do not use any specific function HtmlTextWriter(for example, indentation).

I am currently using the wrapper method to return the string generated HtmlTextWriteras shown below:

var sw = new StringWriter();
var xhtmlTextWriter = new XhtmlTextWriter(sw);
GenerateHtml(xhtmlTextWriter);
return sw.ToString();

My questions:

  • I am trying to get an instance HtmlTextWriterfrom ASP.NET MVC View, but apparently even HtmlHelper does not use this. Did I miss something?

  • Each call GenerateHtmlgenerates small fragments of HTML, usually no more than 1000 characters, but there can be many calls. Should I rewrite dependent code HtmlTextWriterin StringBuilder? Or instead, how about creating an instance HtmlTextWriterthat will be used for all calls (and cleared at the end of iterations).

+3
source share
2 answers

Instead of creating StringBuider and StringWriter, I think using helper.ViewContext.writer will work.

Then the above code example will look like this:

var calendar = new DayPilotCalendar();
if( model != null )
   {
   model.CopyTo( calendar );
   }
if( options != null )
   {
   options.CopyTo( calendar );
   }

HtmlTextWriter writer = new HtmlTextWriter( helper.ViewContext.Writer );

writer.AddAttribute( HtmlTextWriterAttribute.Class, "dayPilot" );
writer.RenderBeginTag( HtmlTextWriterTag.Div );
calendar.RenderControl( writer );
writer.RenderEndTag();  // Close DIV

return( null );         // Don't need to return anything.

: helper.ViewContext.Writer <UL> . . , .

+4

, , MVC.

.

    public static string DayPilot(
        this HtmlHelper helper,
        DayPilotData model,
        DayPilotViewOptions options)
    {
        var calendar = new DayPilotCalendar();
        if (model != null)
        {
            model.CopyTo(calendar);
        }
        if (options != null)
        {
            options.CopyTo(calendar);
        }
        var sb = new System.Text.StringBuilder();
        sb.Append("<div class=\"dayPilot\">"); // allows working around td cellpadding bug in css
        using (var sw = new System.IO.StringWriter(sb))
        {
            using (var tw = new HtmlTextWriter(sw))
            {
                calendar.RenderControl(tw);
            }
        }
        sb.Append("</div>");
        return sb.ToString();
    }

# 2, ...

0

Source: https://habr.com/ru/post/1758057/


All Articles