How do I get over my fears of <% %> in my ASP.Net MVC markup?

后端 未结 12 2047
轻奢々
轻奢々 2021-02-04 07:40

So I totally buy into the basic tenents of ASP.NET, testability, SoC, HTML control...it\'s awesome. However being new to it I have a huge hang up with the markup. I know it co

12条回答
  •  自闭症患者
    2021-02-04 08:08

    Very occasionally use helper methods (I'm NOT talking about the extension helper methods) to write HTML code in the view itself using the Html object model. I wouldnt recomment this unless you have some wierd logic that you cant easily write in the view. As long as the code in .aspx.cs is VIEW code then its fine.

    In your View's .aspx file :

     <%-- render section --%>
     <% RenderTextSection(section); %>
    

    In your View's 'codebehind' you use HtmlGenericControl to create HTML and then the following line to write it out :

    htmlControl.RenderControl(new HtmlTextWriter(Response.Output));
    

    My full method :

    protected void RenderTextSection(ProductSectionInfo item)
    
        {
            HtmlGenericControl sectionTextDiv = new HtmlGenericControl("div");
    
            bool previousHasBulletPoint = false;
            System.Web.UI.HtmlControls.HtmlControl currentContainer = sectionTextDiv;
    
            foreach (var txt in item.DescriptionItems)
            {
                if (!previousHasBulletPoint && txt.bp)
                {
                    // start bulleted section
                    currentContainer = new HtmlGenericControl("UL");
                    sectionTextDiv.Controls.Add(currentContainer);
                }
                else if (previousHasBulletPoint && !txt.bp)
                {
                    // exit bulleted section
                    currentContainer = sectionTextDiv;
                }
    
                if (txt.bp)
                {
                    currentContainer.Controls.Add(new HtmlGenericControl("LI")
                    {
                        InnerHtml = txt.t
                    });
                }
                else
                {
                    currentContainer.Controls.Add(new HtmlGenericControl()
                    {
                        InnerHtml = txt.t
                    });
                }
    
                previousHasBulletPoint = txt.bp;
            }
    
            sectionTextDiv.RenderControl(new HtmlTextWriter(Response.Output));
        }
    

提交回复
热议问题