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

后端 未结 12 1911
轻奢々
轻奢々 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(this HtmlHelper html, IEnumerable rss) where T : IRSSable
        {
            StringBuilder result = new StringBuilder();
    
            if (rss.Count() > 0)
            {
                foreach (IRSSable item in rss)
                {
                    result.Append("").Append(item.GetRSSItem().InnerXml).Append("");
                }
            }
    
            return result.ToString();
        }
    

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

提交回复
热议问题