Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 comes from my hatred of classic ASP, and I can't help but feel like I've entered the twilight zone when I see this.

I don't know what the alternative is (can I use server controls, databinding etc...?)

like image 254
Webjedi Avatar asked Dec 12 '08 17:12

Webjedi


People also ask

How do you manage states in ASP.NET MVC application?

HTTP is a stateless protocol. Each HTTP request does not know about the previous request. If you are redirecting from one page to other pages, then you have to maintain or persist your data so that you can access it further.

How can add Cshtml file in ASP.NET MVC?

Right click the Views\HelloWorld folder and click Add, then click MVC 5 View Page with Layout (Razor). In the Specify Name for Item dialog box, enter Index, and then click OK. In the Select a Layout Page dialog, accept the default _Layout. cshtml and click OK.


1 Answers

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.

like image 79
Chris James Avatar answered Sep 22 '22 11:09

Chris James