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

后端 未结 12 1863
轻奢々
轻奢々 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 07:56

    There are things you can do to help clean up the markup, but I agree it can get a bit tag-soupy.

    • You can make your own HTML helpers to output data using extension methods, so you can hide away some of the if/else logic, iteration, etc
    • Strongly type your views so you can do ViewData.Model.myProperty rather than (MyClasst)ViewData["foo"].myProperty

    For instance this is an extension I made to make an RSS-spitter-outer :)

      public static string RSSRepeater<T>(this HtmlHelper html, IEnumerable<T> rss) where T : IRSSable
        {
            StringBuilder result = new StringBuilder();
    
            if (rss.Count() > 0)
            {
                foreach (IRSSable item in rss)
                {
                    result.Append("<item>").Append(item.GetRSSItem().InnerXml).Append("</item>");
                }
            }
    
            return result.ToString();
        }
    

    So in my front end all I have is <%=Html.RSSRepeater(mydata)%> which is much nicer.

    0 讨论(0)
  • 2021-02-04 07:57

    use server side comments <%-- comment --%> to separate blocks and increase readability. use extra line spacing to separate blocks too (SO seems to be killing off my line spacing here for some reason).

            <%-- Go through each testimonial --%>
            <% foreach (var testimonial in ViewData.Model.Testimonials) { %>
    
            <div class="testimonialFrame">
                <div class="testimonialHeader"><%= testimonial.summaryText %></div>
    
    
                <%-- Show video if available --%>
                <% if (string.IsNullOrEmpty(testimonial.Video.FullURL) == false) { %>
    
                <div  style="padding-top:12px">
                    <% Html.RenderAction("YouTubeControl", "Application", new { youTubeId = testimonial.Video.FullURL }); %>
                </div>
    
                <% } %>
    
                <div class="roundedBox" style="margin-top:15px">
                    <div id="txtTestimonialText" class="testimonialText paddedBox"><%= testimonial.TestimonialText %></div>
                </div>
    
                <div class="testimonialFooter"><%= testimonial.name %></div>
            </div>
    
            <% } %>
    
    0 讨论(0)
  • 2021-02-04 08:01

    Avoiding tag soup reading might be helpful. Generally you can not use server controls (some might work though), there is no postback or viewstate. I don't think you can use databinding (again there might be exceptions, I'm not sure how ASP.NET MVC treats server controls in the view.) - the easiest method to "databind" something is to pass a list or array of data into the view and use foreach to build HTML out of it.

    0 讨论(0)
  • 2021-02-04 08:04

    I like to make the syntax highlighting for my "<% %>" tags very similar to the background color. I use a black background and a silver-ish (don't have the specific colour on hand atm) colour for my "<% %>" tags. That plus the other suggestions here should have make your code more readable. Of course, you can always try another view engine (that's the beauty of MVC!)

    0 讨论(0)
  • 2021-02-04 08:04

    If you're talking about the HTML from rendered controls, I'm afraid it doesn't get any better just because you've got a nice standards-based wrapper around your View in MVC. Without adapted controls, the output is still circa-1995 crappy nested table code.

    Thanks, Microsoft!

    0 讨论(0)
  • 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));
        }
    
    0 讨论(0)
提交回复
热议问题