11

Uses Razor as a return to the classic ASP

 2 years ago
source link: https://www.codesd.com/item/uses-razor-as-a-return-to-the-classic-asp.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Uses Razor as a return to the classic ASP

advertisements

I'm looking at the Razor engine and I'm wondering how it's "different" compared to the initial classic ASP implementation where the server-side and front-end code where in the same page.

Why should I care about Razor?


In classic ASP, you used to have business code in your file ("Fetch stuff from the database and act on it").

In ASP.net MVC - regardless if you use the ASPX or Razor View Engine - you are dealing with View Logic. Things like "I have 20 Employees, display them in a table" or "If this number is negative, display it in red instead of black".

The business logic is in the controllers and lower. The controller then passes the business data to the view through a view model. The View then only has code that handles displaying it, which is usually trivial but can have a few logic branches of it's own ("Display Dates in the Users Locale" or "Display male and female employees in separate tables")

You can make the mistake of putting business logic here. Say, employees hired before 2008 are eligible to a Certificate of Loyalty. So your table has a column "Print Certificate" that is only displayed for these. The simple, but wrong approach is to put an if-statement:

@if(employee.HireYear <= 2008) {
    Html.ActionLink("Print Certificate","Certificate","Cheese",
        new { id = employee.Id }, null);
}

This works, but is wrong because the view now contains business logic. The correct approach is adding a new bool field to the ViewModel. Since it contains an IList<Employee> in this example, it means creating another EmployeeWithCertificateEligibility class, or better, having separate lists for eligible and ineligible employees. It's somewhat common though to have business logic spill into the view, sometimes in form of an HtmlHelper extension method.

Edit: You compare it to the "initial classic asp implementation". That can mean three things: Classic ASP, ASP.net WebForms or ASP.net MVC with the WebForms/ASPX view engine. My example concerns the first two cases. If you already know the whole MVC stuff and just wonder about the differences between the Webforms and Razor View Engine: Conceptually they are the same, Razor is just a lot less verbose and cleaner.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK