Tips for Migrating from Web Forms to Razor Pages
ASP.NET web forms were the precursor to the current ASP.NET core. It was introduced as a convenient event-driven development model for writing web applications for users who wanted to migrate their WinForms applications by providing the same interface in web pages. However, technology has evolved rapidly over the years, and heavier frameworks have given way to lighter frameworks that scale up quickly and must be platform-independent.
To support other platforms besides Windows, Microsoft has developed a lightweight framework that can be deployed on non-Windows platforms called .NET Core. This framework is designed to be platform-independent and provides developers with a versatile tool for building web applications that can be deployed across multiple platforms.
Ready to Try It Out? Download ComponentOne Today!
Understanding the Differences Between Web Forms and Razor Pages
Microsoft introduced Web Forms in ASP.NET as an event-driven programming model. It offers a set of server controls that enable developers to build web pages equivalent to Windows Forms applications. Web Forms includes many details of HTML, CSS, and JavaScript, allowing developers to focus on application logic.
On the other hand, Razor Pages is a lightweight web framework introduced in ASP.NET Core. It is designed to be simple and user-friendly, making it an excellent choice for building web applications. It uses the Razor syntax to create HTML templates, which are combined with C# code to create dynamic web pages.
While there are similarities between Web Forms and Razor Pages, there are also significant differences between the two frameworks. Web Forms provides a more abstract way of building web pages, while Razor Pages require developers to have a deeper understanding of HTML, CSS, and JavaScript. Additionally, Razor Pages are more modular and testable than Web Forms, making it a better choice for building modern web applications.
This article will explore some similarities and differences between Web Forms and Razor Pages. We will cover:
Processing Request
An ASP.NET Web Forms application consists of a .aspx page for the template code and a Code Behind page (.aspx.cs page) for processing its page. This page is inherited from System.Web.UI.Page. The code behind the page includes a Page_Load lifecycle hook that is triggered on every request made to the server, including both Post back and non-Post back requests, such as Callback requests.
namespace GridViewIntro
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData(C1GridView1);
}
}
….
}
}
In contrast to Web Forms, a Razor Page inherits from the PageModel class. This class includes OnGet and OnPost methods, which are triggered for GET and POST requests made to the server, respectively. Along with these methods, we can define public properties on the page that will be used in the content page (UI).
namespace FlexGridIntro.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
private testdbContext db;
[BindProperty]
public DateTime Today { get; set; }
public IndexModel(ILogger<IndexModel> logger, testdbContext _db)
{
db = _db;
_logger = logger;
}
public void OnGet()
{
People = SampleData.GetData(10);
Today = new DateTime(2020, 06, 07);
}
public void OnPost()
{
if (ModelState.IsValid)
{
//code
}
}
}
}
Master Pages vs. Layout
Web Forms applications use Master Pages to maintain a common UI for the entire application. This includes elements such as the main menu, navigation menu, header, footer, and more. In contrast, Razor Pages use Layout to achieve the same goal of consistent page content across the application.
Both Master Pages and Layouts utilize the same concept of writing consistent content in a single place. In Master Pages, a Placeholder is used to specify where the target page content should be placed within the master page. Similarly, in Layouts, a @RenderBody() directive is used to specify where the page's content should be inserted within the layout.
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
While the Razor pages use the RenderBody to place the target page content.
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
Model Binding
In Web Forms, Model Binding is achieved using the Request object. Developers can access values from the Request object and manually bind them to model properties. However, this process can be time-consuming and prone to errors. The developer is responsible for ensuring that the mapping of values to the correct properties is handled correctly.
public class Organization
{
public string Name { get; set; }
public string Email { get; set; }
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
var organization = new Organization();
organization.Name = Request.Form["Name"];
organization.Email = Request.Form["Email"];
// code to save in DataBase
}
In contrast, Razor Pages use a more streamlined approach to Model Binding. The framework automatically maps properties to the Model based on naming conventions, making it a simple and less error-prone process for developers. Furthermore, the binding behavior can be customized using attributes such as [BindProperty] or [Bind].
namespace FlexGridIntro.Pages
{
public class IndexModel : PageModel
{
[BindProperty]
public DateTime Today { get; set; }
}
}
<input asp-for="@Model.Today" />
UserControls
In WebForms, the UserControl is a reusable UI component that allows you to create a custom control. It provides a set of properties, methods, and events, like a custom server control, but with a simpler development approach. To create a UserControl, you can create an ASP.NET User Control file (.ascx) in Visual Studio, which contains both HTML and server-side code for the control. After creating the UserControl, you can add it to a WebForm in the same way as any other server control.
<%@ Register TagPrefix="uc" TagName="MyControl" Src="~/Controls/MyControl.ascx" %>
The code snippet below registers the UserControl named "MyControl.ascx" located in the Controls folder and makes it available for use on the page. You can then add the UserControl to the page using the following code:
<uc:MyControl runat="server" />
This code instructs the page to use the registered UserControl with the "uc" tag prefix and "MyControl" tag name. The runat="server" attribute indicates that the UserControl will be processed on the server. You can place this code anywhere on the page where you want the UserControl to be rendered.
In Razor Pages, a Partial View is similar to a UserControl in WebForms. To create a Partial View, you need to create a Razor file with the ".cshtml" extension and define the UI component within it. Once the PartialView is defined, it can be used in other Razor Pages or Partial Views.
Use a Partial View in a Razor Page; you need to specify its path using the Html.Partial helper method. This method renders the Partial View at the specified path within the Razor Page.
For instance, let's say we have a Partial View named "_MyPartialView.cshtml" located in the "Shared" folder, and we want to use it in a Razor Page. To do this, we can use Html.Partial helper method like this:
@Html.Partial("~/Views/Shared/_MyPartialView.cshtml")
This will render the Partial View on the page at the location where the Html.Partial method is called. We can also pass data to the PartialView by passing a model to it. For instance, if we have a model named MyModel, we can write the code like this:
@Html.Partial("~/Views/Shared/_MyPartialView.cshtml", MyModel)
Partial Views in Razor Pages offer a flexible way to create reusable UI components that can be used across multiple pages.
After finding the similarities between the WebForms and Razor pages, we would understand how the application’s technology can be changed and migrated to the latest technology. We will discuss here the required steps to migrate the application.
Step 1: Evaluate the Existing Codebase
The first step in the migration process is to evaluate the existing Web Forms application code to determine which application parts need to be migrated. This includes analyzing the application's business logic and user interface. Identify which parts of the code can be reused and which must be rewritten.
Step 2: Refactor the Business Logic
Once you have evaluated the existing application code, the next step is to refactor the business logic to make it more modular. This requires finding the application logic from the current Web Forms application and rewriting it as per the need to put it at its appropriate place in the Razor app. This code can then be used to create new Razor Pages and interact with them as needed.
Step 3: Create the Razor Pages
Create the Razor Pages that will replace the Web Forms pages by creating a new Razor Pages project. Add the necessary pages and components to the project. Make sure to use a consistent layout for the pages and components to ensure the application is easy to maintain and update.
Step 4: Migrate the User Interface
Migrate the user interface from the Web Forms pages to the Razor Pages by converting the HTML, CSS, and JavaScript code used in the Web Forms pages to the Razor syntax used in Razor Pages. It is essential to test the pages thoroughly to ensure they work correctly.
Step 5: Test and Refine the Application
The last step in the migration process is to test and refine the application to ensure it works correctly. This involves testing the application thoroughly to ensure all functionality works as expected. It is also important to get user feedback to identify any issues or areas that need improvement.
Conclusion
Migrating from Web Forms to Razor Pages requires careful planning and execution. It is important to evaluate the existing codebase, refactor the business logic, create new Razor Pages, migrate the user interface, test and refine the application, and deploy it to the production environment. By following these steps, we can migrate our Web Forms application to the latest technology and take advantage of the benefits of the Razor Pages framework.
Ready to Try It Out? Download ComponentOne Today!