Click here to Skip to main content
15,860,972 members
Articles / Web Development / ASP.NET

Fast Postback and Model Binding

Rate me:
Please Sign up or sign in to vote.
4.86/5 (28 votes)
27 Apr 2014CPOL6 min read 36.9K   989   37   10
Faster way to save data on postback and simplified model binding with ASP.NET controls

Introduction

When ASP.NET MVC came to the market, many developers simply had switched to MVC because they had seen two major flaws in ASP.NET Web Form architecture.

  1. Testability
  2. Postback model

While other stuff like ViewState, Static Control Ids were easy to overcome but Postback model and testability were hard to replace. I would not like to debate on separation of concerns in this article.

This article provides you an easy workaround on how you can omit all unnecessary life cycle events simply by using Generic Handler instead of posting data back to the same page. Side by side, you will be able to retain the beauty and flexibility of Lifecycle of your page for first time load or whenever needed. In this approach, you don't need to abandon any rich Server Side Controls which are designed to provide you a huge set of flexibility and Rapid Application Development.

Background

This article assumes that you have a basic understanding of ASP.NET page life cycle and postback. You should also know a little bit about what is generic handler. You may wish to brush up your knowledge with the following articles:

Current Approach

Consider you are developing a form where you require the user to fill employee data and submit. When the form is submitted, by default, it is submitted to the same page. Here, the following things occur:

  1. All controls get initialized and default data is populated to each control.
  2. Populate data of controls like drop down list, etc. If you don’t populate it manually, it might be maintained by ViewState. Well, I would not go into detail to keep this article focused on my topic.
  3. All ViewState data is applied to their respective controls (Load ViewState).
  4. Controls value gets over-written with the posted form data (Load PostbackData).
  5. PageLoad event gets triggered. You might have excluded the code execution in this by putting all your code within if(!IsPostback) condition.
  6. Click event triggers. This is the place where you are getting values of your server controls to your entity model. Then, you save the data to the database.
  7. Redirect to some other page.

The problem in web form while saving data: You might be observing that your only job is to save form data to the database and then, redirect to other page. So, instantiating controls, populating values to controls, loading view state, copying data from controls to your model are unnecessary and an overhead. If you wish to redirect to another page after saving the data, why playing with controls, ViewState and life-cycle?

Suggested Approach

The new approach suggests the idea where we don’t actually post the data back to the same page but, to a generic handler (.ashx). This would include the following steps:

  1. Post your data to generic handler. Bind posted form data to Entity model.
  2. Save model to the data base.
  3. Redirect to other page.

To perform the first step, you can bind posted form data to the model using Bind method of ModelBinder class. In this method, I have simply looped through all the property of the model entity and fetched the corresponding form data to populate it.

Image 1

The above picture is the screen shot of the demo application.

Using the Code

With this article, I have provided a sample which performs the basic CRUD operations on Employee using Fast Postback approach. The sample also provides you an easy way to bind form data with entity and entity data with controls.

Using this approach involves the following steps:

  1. Create a new Generic Handler, and call method to bind data. Write your code to save your data here in ProcessRequest method. Then, redirect to other page.
    C#
    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.HttpMethod == "POST")
        {
            Models.Employee emp = ModelBinder.Bind<models.employee>();
            using (CompanyEntities db = new CompanyEntities())
            {
                if (context.Request.QueryString["action"] == "create")
                    db.Employees.Add(emp);
                else
                    db.Entry(emp).State = EntityState.Modified;
                db.SaveChanges();
            }
            context.Response.Redirect("~/Employee/List.aspx");
        }
        else
        {
            context.Response.Write("Either you are trying to hack my system 
                                    or you have visited this page accidentally.");
        }
    }
  2. In your WebForm page, set PostBackUrl property of your submit button to the newly create Handler.
    HTML
    <div class="form-submit">
                <asp:button id="btnSubmit" runat="server" 
                 text="Submit" postbackurl="~/Employee/Save.ashx?action=edit" />
    </div>

Here, I assume that all the required authentication and authorizations have been processed at HttpModule level. Else, you may wish to consider manual authentication/authorization in your Handler.

Image 2

The above picture is the screenshot of the demo application.

Model Binding

The sample code provided also provides a basic approach to bind models with Controls and form data. You may extend this code to implement things based on your need. If you wish to implement the model binding at a detail level, you may wish to consider this link.

Points of Interest

  • The provided sample has also used FriendlyUrls for ASP.NET. So, for beginners, it might act as a sample on how you can easily generate Restful URL in ASP.NET web forms.
  • The provided sample also uses entity framework. So, for beginners, it might act as a very light-weight sample on using entity framework.
  • The attached code can also be used as a sample for beginners on how a generic handler can be used for such kind of operation in a situation where only a set of code processing is needed at server side.

Future Consideration

Well, this article has just provided you the idea and sample implementation, I am planning to create a small library to handle more complex situations also with this approach. Some of them include:

  • Binding more complex controls with model
  • Binding form data to IEnumerables
  • Transferring the control back to the page when exception/error occurred

I am also working on some other approaches along with the approach discussed in this article. These approaches include:

  1. Using PageMethods to save data instead of postback (Helps to keep similar logic in the same page)
  2. Using Web Service. Creating a different class to keep all save (create/edit) and delete operation together. This will be helpful if you want to expose the web service to 3rd party.
  3. Using Web API. Yes, as in Visual Studio 2013, you can parallely create Web API in the same project, it is a good idea to move all create/update and delete logic to web API and keep only display logic (presentation) to WebForm projects. This way, you can use the flexibility and rich server controls of Web Form in your Rapid Application Development projects and side by side keep all your database operations faster. This kind of architecture will also support exposing web API to 3rd parties if you wish to do so.

I am working on the above 3 approaches too and once I am able to architect my solution properly using either of these approaches, I will publish it within the same or different article depending on the content and architecture. I would love to hear the pros and cons of these approaches from the experts so that we can make beautiful web form projects perform faster too.

Conclusion

Wherever you want to improve performance of your web form application, you can easily switch to this approach for simple web forms along with taking advantage of page LifeCycle and server controls during first time load. Moreover, this approach may exist side by side with the existing post back approach for some complex pages where you may not wish to implement this approach.

I always welcome your feedback/comment/suggestions to improve it further.

History

  • Aug 14, 2013
    • First version created
  • Apr 27, 2014
    • Article update with attached database
    • Opened discussion on 3 more approaches

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
Anurag Gandhi is a Freelance Developer and Consultant, Architect, Blogger, Speaker, and Ex Microsoft Employee. He is passionate about programming.
He is extensively involved in Asp.Net Core, MVC/Web API, Node/Express, Microsoft Azure/Cloud, web application hosting/architecture, Angular, AngularJs, design, and development. His languages of choice are C#, Node/Express, JavaScript, Asp .NET MVC, Asp, C, C++. He is familiar with many other programming languages as well. He mostly works with MS SQL Server as the preferred database and has worked with Redis, MySQL, Oracle, MS Access, etc. also.
He is active in programming communities and loves to share the knowledge with others whenever he gets the time for it.
He is also a passionate chess player.
Linked in Profile: https://in.linkedin.com/in/anuraggandhi
He can be contacted at soft.gandhi@gmail.com

Comments and Discussions

 
Questionmvc core binding in post back not working Pin
vineykum10-Jan-22 18:00
vineykum10-Jan-22 18:00 
SuggestionWeb API Pin
Neetflash1-May-14 23:44
Neetflash1-May-14 23:44 
GeneralRe: Web API Pin
Anurag Gandhi2-May-14 3:12
professionalAnurag Gandhi2-May-14 3:12 
Questionhi Pin
foladi28-Apr-14 17:52
professionalfoladi28-Apr-14 17:52 
GeneralMy vote of 5 Pin
Volynsky Alex27-Apr-14 10:19
professionalVolynsky Alex27-Apr-14 10:19 
GeneralRe: My vote of 5 Pin
Anurag Gandhi15-Apr-21 6:12
professionalAnurag Gandhi15-Apr-21 6:12 
Questionhi Pin
foladi26-Apr-14 10:20
professionalfoladi26-Apr-14 10:20 
AnswerRe: hi Pin
Anurag Gandhi27-Apr-14 4:53
professionalAnurag Gandhi27-Apr-14 4:53 
SuggestionMy vote of 4 Pin
Champion Chen5-Mar-14 15:33
Champion Chen5-Mar-14 15:33 
GeneralRe: My vote of 4 Pin
Anurag Gandhi5-Mar-14 18:07
professionalAnurag Gandhi5-Mar-14 18:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.