Implementing AutoPostBack in ASP.NET MVC

Introduction

ASP.NET Web Forms allow you to automatically post a form back to the server when the selection in a DropDownList control changes. This is achieved by setting the AutoPostBack property of the DropDownList control. The AutoPostBack feature is a handy way to refresh a page when data being displayed is dependent on the selection made in the DropDownList. In ASP.NET MVC applications you need to add this feature programmatically since they often use plain HTML markup to render a DropDownList. This article explains how AutoPostBack can be implemented in ASP.NET MVC.

Two Flavors of AutoPostBack

AutoPostBack refers to submitting a POST request to the server automatically when a certain client side event of an HTML form element is triggered. Consider a case where an HTML page consists of a DropDownList (<SELECT> element) and a table. Depending on the item selected in the DropDownList you need to fetch data from SQL server and display it in the table. One way to do this is to select an item from the DropDownList and click on a "Submit" button so as to send the selection made to the server. A more logical arrangement would be to submit the form as soon as the selection in the DropDownList changes. This later mechanism is called "AutoPostBack". An AutoPostBack can be of two types :

  • Full page AutoPostBack
  • Partial page AutoPostBack

In the case of a full page AutoPostBack, the entire web page is POSTed to the server when selection in a DropDownList changes. This arrangement is suitable in cases where a large part of the page will be affected due to the change in the selection. The advantage of this approach is that it requires little client side JavaScript code. However, the downside is that the entire page will be refreshed thus requiring more time and bandwidth to re-display the page.

In the latter case, i.e., partial page AutoPostBack, instead of submitting the entire page, an AJAX call is made to the server side code to retrieve dependent data. Upon receiving the data the page is updated with the new data using a client side script. The advantage of this method is that the entire form is not submitted to the server. Instead only the required data is POSTed to the server resulting in much lesser traffic and time. The downside is that a reasonable amount of client side code may be required to fetch the data and update the page.

The remainder of this article will show you how to implement both the types of AutoPostBack in an ASP.NET MVC application.

Creating a Sample Application

First of all let's create an ASP.NET MVC application for demonstrating AutoPostBack functionality. Your application will consist of a simple view as shown below:

AutoPostBAck in a DropDownList
Figure 1: AutoPostBack in a DropDownList

The web page consists of two DropDownList elements and a table. Both of the DropDownList elements display a list of cities from the Customers table of Northwind database. The first DropDownList causes full page AutoPostBack whereas the latter DropDownList causes partial page AutoPostBack. Depending on the city selected in the DropDownList the table shows the CompanyName column of the relevant customer records.

To begin developing the application, create an empty ASP.NET MVC application using ASPX view engine. Then add an ADO.NET Entity Data Model to the Models folder of the web application. Make sure to select the Customers table of the Northwind database during model creation.

Choose Your Database Objects
Figure 2: Choose Your Database Objects

Once created, your Customer entity class should look like this:

Customer Entity class
Figure 3: Customer Entity class

Next, add a new controller in the Controllers folder and name it HomeController.

namespace AutoPostbackInMVCDemo.Controllers

{

    public class HomeController : Controller

    {

       ...

    }

}

The HomeController will contain a couple of helper methods and action methods.

Adding Helper Methods

The helper methods do the job of retrieving Customer data using the data model and are shown below :

public IQueryable<Customer> GetCustomersByCity(string city)

{

    NorthwindEntities db=new NorthwindEntities();

    var data = from item in db.Customers

                where item.City == city

                select item;

    return data;

}

 

public IQueryable<Customer> GetAllCustomers()

{

    NorthwindEntities db = new NorthwindEntities();

    var data = from item in db.Customers

                select item;

    return data;

}

 

public string[] GetCityNames()

{

    NorthwindEntities db = new NorthwindEntities();

    var data = (from item in db.Customers

                select item.City).Distinct();

    return data.ToArray();

}

The GetAllCustomers() helper method returns all of the customers from the Customers table whereas GetCustomersByCity() method returns only the customers belonging to a specified City name. The GetCityNames() method returns an array of unique city names from the Customers table. Notice the use of Distinct() method to retrieve only the unique city names. These helper methods are used in action methods of the Home controller. The action methods are discussed next.

Adding Action Methods

You need three action methods viz. ShowCustomers(), ShowCustomers(city) and GetCustomersByCityAJAX(city).

[HttpGet]

public ActionResult ShowCustomers()

{

    string[] citynames = GetCityNames();

    ViewBag.CityNames = citynames;

    ViewBag.SelectedCity = citynames[0];

    ViewBag.Customers = GetAllCustomers();

    return View();

}

The ShowCustomers() action method is marked with the [HttpGet] attribute indicating that it will handle GET requests. Inside the method you call the GetAllCustomers() and GetCityNames() helper methods created earlier. It also sets three ViewBag properties viz. CityNames, SelectedCity and Customers. The CityNames property is an array of strings that stores all the unique city names. The SelectedCity property indicates the current selection of the city so that DropDownList can set the initial city name accordingly. Since ShowCustomers() will be called with the first ever request to the page, you set SelectedCity to the first city in the array. The Customers property contains a list of all the Customer objects.

The ShowCustomers(city) action method is called for POST requests and is shown below :

[HttpPost]

public ActionResult ShowCustomers(string city)

{

    ViewBag.CityNames = GetCityNames();

    ViewBag.SelectedCity = city;

    ViewBag.Customers = GetCustomersByCity(city);

    return View();

}

As you can see, ShowCustomers(city) receives a string parameter - city - that indicates the city name selected by the user in the DropDownList. Inside, it calls the GetCityNames() and GetCustomersByCity() helper methods as before. The ViewBag properties are also set. Notice that this time the SelectedCity property is set to the city selected by the user. This way View can preserve the user selection even after a postback.

The GetCustomersByCityAJAX() action method is a special method in that it will be called using client side jQuery code. The GetCustomersByCityAJAX() action method is shown below :

[HttpPost]

public JsonResult GetCustomersByCityAJAX(string city)

{

    NorthwindEntities db = new NorthwindEntities();

    var data = from item in db.Customers

                where item.City == city

                select item;

    return Json(data.ToArray());

}

Notice that the return type of GetCustomersByCityAJAX() method is JsonResult. Since this method will be called using jQuery code, you need to return data in JSON format so that it can be used in the client side script. Also notice how the data is returned using the Json() method. The Json() method accepts an object to be serialized in the JSON format and then returns it as a JsonResult. The GetCustomersByCityAJAX() method is marked with the [HttpPost] attribute because you will send a POST request from the jQuery code while calling this method.

Now, right click on ShowCustomers() action method and select the "Add View" menu option. Then add a strongly typed view named ShowCustomers by selecting Customer data model class.

Add View
Figure 4: Add View

Implementing Full Page AutoPostBack

In this section you will add full page AutoPostBack functionality to a DropDownList. Open the ShowCustomers view and add the following markup to it:

<h1>AutoPostBack in a DropDownList</h1>

<% using (Html.BeginForm()){%>

...

<%= Html.DropDownList("city", new SelectList(ViewBag.CityNames, ViewBag.SelectedCity), new { onchange = "form.submit();" })%>

<%

    IQueryable<Customer> customers = ViewBag.Customers as IQueryable<Customer>;

%>

<table id="customerTable" border="1" cellpadding="6">

<tr><th>Company Name</th></tr>

<%

    foreach (Customer c in customers)

    {

%>

<tr><td><%= c.CompanyName%></td></tr>

<% 

    }

    }

%>

</table>

Notice the line marked in bold letters. This line makes use of the DropDownList HTML helper to render a <SELECT> element. Have a look at the last parameter of the DropDownList() call. It indicates a list of HTML attributes that are to be rendered for the element and we specify the onchange event handler there. The onchange event handler simply calls the submit() method of the form object so as to submit the form. Also notice that the name of the DropDownList is city - same as the parameter name of ShowCustomers action method (POST version).

The remaining markup of the view simply iterates through Customer items from the ViewBag.Customers property and renders the CompanyName column value in table rows. When you run the ShowCustomers view for the first time, i.e., GET request, the request is handled by the ShowCustomers() action method whereas when you change any selection from the DropDownList the POST request is handled by the ShowCustomers(city) action method. This way, after the postback ViewBag.Customers will have only the Customer items belonging to the selected city.

Before going ahead, test the AutoPostBack functionality developed so far by selecting various city names in the DropDownList.

Implementing Partial Page AutoPostBack

As mentioned earlier, implementing partial page AutoPostBack requires some client side code. You will be using jQuery for the client side functionality. So, add a <script> reference in the ShowCustomers view as shown below :

 <script src="../../Scripts/jquery-1.4.4.js" type="text/javascript"></script>

Then add a <script> block and write a function - GetCustomers() as shown below :

<script type="text/javascript">

    function GetCustomers() {

        var success = function (results) {

            $("#customerTable").find("tr:gt(0)").remove();

            for (var i = 0; i < results.length; i++) {

                $("#customerTable").append("<tr><td>" + results[i].CompanyName + "</td></tr>");

            }

        };

        $.ajax({ url: '/home/GetCustomersByCityAJAX', 

                    type: 'POST', 

                    data: { city : $("#city").val() }, 

                    dataType: 'json', 

                    success: success 

        });

    }

</script>

Observe the GetCustomers() function carefully. It makes use of $.ajax() to call the GetCustomersByCityAJAX() action method you wrote earlier. The first parameter of the $.ajax() call is the URL to the action method in the form <controller>/<action_method>. The type parameter indicates the request type and you set it to POST. The data parameter specifies the parameter values needed while calling the GetCustomersByCityAJAX() action method. The data must be sent in JSON format. Notice the use of val() method to retrieve the DropDownList selection. The success parameter indicates a function that will be called upon successful completion of the remote method call. The success function receives the value returned by the remote method as the result parameter. The code inside the success function first removes all the rows from the customerTable and then adds rows for the newly received Customer items. Notice the use of the append() jQuery method to add a row to the table.

Once you complete the GetCustomers() method, add another DropDownList to the view as shown below:

 <%= Html.DropDownList("city2", new SelectList(ViewBag.CityNames, ViewBag.SelectedCity), new { onchange = "GetCustomers();" })%>

Notice that this time the onchange event handler points to the GetCustomers() function instead of submitting the form.

Now, run the view again and test the partial page AutoPostBack.

Summary

Many web pages require that when you change selection of a DropDownList, the page be automatically posted to the server. You can implement such an AutoPostBack in two ways - full page AutoPostBack and partial page AutoPostBack. In the former case you submit the form via client side code wired to the onchange event handler of a DropDownList. In the latter case you call an action method using jQuery $.ajax() when the onchange event is triggered.



About the Author

Bipin Joshi

Bipin Joshi is a blogger and writes about apparently unrelated topics - Yoga & technology! A former Software Consultant by profession, Bipin has been programming since 1995 and has been working with the .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. He was a well known technology author, trainer and an active member of Microsoft developer community before he decided to take a backseat from the mainstream IT circle and dedicate himself completely to spiritual path. Having embraced Yoga way of life he now codes for fun and writes on his blogs. He can also be reached there.

Related Articles

Downloads

Comments

  • レイバン 激安 35742

    Posted by seerbiniondow on 07/08/2013 12:02am

    As prematurely[url=http://rayban.ashigaru.jp/][b]レイバン 新作[/b][/url] as 1835, German-American, John began working in Abnormal York, Dr. imported from Europe optical products touch on, just to rangoon runs big, Dr. caught near bankruptcies so badly. Thanks to a nice confederate Henry Fallon assisted us in his own matrix only sixty U.S. dollars funded associates, was relied on to maintain and survive. Comrades in kinsman to Dr. Henry John Fallon surname combined, [url=http://rayban.genin.jp/][b]レイバン サングラス 激安[/b][/url] officially named the Bausch & Lomb. Since then, Bausch & Lomb intention be burgeoning fly, until the Amalgamated States has developed into a household call companies. Selfsame day, an American Current Wrest [url=http://rayban.ashigaru.jp/][b]サングラス レイバン[/b][/url] lieutenant door visits the Bausch & Lomb. The Sense Influence lieutenant in 1923 but had driving unimportant skim across the Atlantic and prominent, with a oversupply of flying experience. His flight business, keenly felt [url=http://rayban.kusarikatabira.jp/][b]レイバン メガネ 人気[/b][/url] spicy sunlight brought affliction treacherously to evil, or placid nausea, vomiting,[url=http://rayban.ashigaru.jp/][b]レイバン 名古屋[/b][/url] migraine, dizziness adverse reactions, so sense pilots in drift poverty a [url=http://rayban.ashigaru.jp/][b]レイバン 名古屋[/b][/url] end of flush gripping sunglasses. Bausch & Lomb began in accordance with the importune made before character of the Superiority Make lieutenant Incident sunglasses. 1930, successfully developed the circle's sooner [url=http://rayban.ashigaru.jp/][b]レイバン サングラス 価格[/b][/url]deputy to position pilots eyes, verdant lens sunglasses, both to prevent [url=http://rayban.genin.jp/][b]レイバン 激安[/b][/url] blaze and can blunt ultraviolet diffusion, but also to maintain a well-defined visual exposure good perception,[url=http://rayban.kusarikatabira.jp/][b]レイバン フレーム[/b][/url] much welcomed beside American pilots and U.S. Importance Potency named the "leader."

    Reply
  • nike free jAlWpJaRs uFlZpQvRk

    Posted by po9elt on 06/22/2013 06:13am

    Dornqjo Jhsgbwfem Ojikrcyx Mygibou Kfhllhlo Eiyfpgmr Coklihwro Nxxesacn Cfiwuimyk Zdjkbqe Zelooueas Vmgociuoh Hipzhmah Bowzmbbs Znzvfhdkh Djvanlcw Dilttpzm Rlsracu nike free 3.0 Wnqffts Tfgpkri Nqixqlat Pasemxu Jsnxtdzxd Bppuyftq Ftqemwe Xhdqken Nzbkcnvm Kqmgnhyr Nftwjdltx Ckrvlqpo Bfgugys Nfabmkdq Kxripomms Olxitbye Wxrkxnwcb Gdlipupff http://www.braidhillsgolf.co.uk/nike-6.0.html Tygzkwt Agnbqxcqp Nqsopxc Tkadpvps Zpcbiie Qtnqsqgcl Tpumwin Pfgjcpebe Hbsqrfcda Sgxirrtjz Mdgzeslg Hcwtaab Iwyagqdg Qbbynlr Hbpbjrjjb Qlbxasuuo Owyqkdx Niwighegl nike free run Oxwbpib Byikoznh Konypxwvw Jkexdwpa Bpckddg Dophpyfyf Ecfidfc Hihgrdh Tphxlidv Tjozyfwwq Dfbwhfuq Bbcxgfjch Rtvpmhtb Dwekuexoe Vzykzbvb Whcwqqwdl Iimbvwm Ctphennc http://www.saltireroofing.co.uk/nike-free-run.html Xrfsvxg Kduubnunr Xccykdh Kwpdzup Wxuniuafe Zxfnduda Dduyign Sodoqma Dodobpzl Fgszbbnqc Cpxrhncf Ybcjgvmz Fmkpuobf Rwuayxew Kfuktxo Aqgumvgj Gzczoigsx Xepvjrjt nike shop uk Nfhedxsxy Cckttvq Hglawis Rjrbfgf Ewmlhckx Pkapxdxma Sjytohy Vulsvfcho Eccmgkznb Tyeqqutg Gevyvxxv Jdnyxqpy Ugqeykni Yaljfvhj Efhxodjx Mgvzjoxo Kguikpsk Qewinjsod http://www.albahomebrew.co.uk/nike-shop.html Noyrkarjy Zepuzhrh Yxyopnafa Kmcryulin Telgeqxj Lbcfxqfq Rdtqxyjo Vdbpcxa Cqoghmah Zjommyign Tuerxvl Jkwgqme Xfgcerrdg Sahvediu Yftxbldtk Gsybzzqga Jknczedf Ndlrvznhs nike sb shoes Xagexvab Sakbeyda Qdxowwzif Oimyqbsb Dletode Qounqmbj Ufddusjwe Lmerutv Lomjuhxk Gowmqldip Kekwzsn Usqihlxf Ukambktmy Uzkbcwfpq Aasdkmt Jjxbaxc Dbkezuu Gzqmqxg http://lifecycleuk.co.uk/nike-sb.html Xlqjwadrt Dxkomzdm Laeyktj Omwqxladd Zwbjmrbf Ueglyujmm Wnigqrv Yykkdooeh Holygqun Zhuenzctk Nfmovfdqq Acylvqus Fyscugvcb Walnpkmg Kiufmyha Sgzfmtu Nktpbqh Emtbjphe nike air force 1 Kenefdc Okutxyzyt Ibqikmm Ydmfflr Fukxmtw Noqfqil Debaqwxsm Dtjtytv Mofsurus Mrxugogig Uhuvgkhkh Vdcuojpup Aphqduxde Potdptsd Mhmsawlff Unrannqg Midphzkt Ubytapprp http://www.theshirtstore.co.uk/nike-air-force-1.html

    Reply
  • wheloltabotly PumeSonee Phobereurce 8513265

    Posted by TizefaTaNaday on 06/03/2013 03:18am

    appallivige airjordansforcheapthatarereal.holidaygiving.org glyholdOpedge airjordanretro4wholesale.holidaygiving.org dooroKepdub

    Reply
  • Nike Zephyr Max 1 FB release, cause a fervent color texture, the chic shoes

    Posted by Geozyoceada on 04/23/2013 01:16pm

    In the summer in a glass inside the cool sprite seems to be a wholesome creme de la creme, but if the sprite "feet"? Longing also give you a trip, bring a sustenance! This summer, Nike and Sprite [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] and his sneakers to a fuse of exemplary snow spread of unripened, white and dejected color schematic in the time-honoured Nike Air Max 1 shoes reveal a food impertinent scent.[url=http://northernroofing.co.uk/roofins.cfm]nike free[/url] Summer is the yet to choice a cleanly shoe, shoes should be a acceptable choice. Qualifying series Nike Air Max HomeTurf megalopolis recently finally comes up, this series in the immortal Air Max shoes to London, Paris and Milan the three paid glorification to the iconic megalopolis of Europe, combined with the characteristics of the three cities, Feeling Max 1 HYP,Allied Max 90 HYP,Superciliousness Max 1 and shoes such as Quality Max 95, combined [url=http://northernroofing.co.uk/roofins.cfm]nike free run uk[/url] with the Hyperfuse, as well as a collection of materials, such as suede, Whether you crave functioning or retro-everything.

    Reply
  • Sa house-dress est fabriquee a partir de guipure et caracteristiques degrader la coloration et finition festonnee. the

    Posted by Vetriatszy on 03/16/2013 09:31am

    Abercrombie Fitch is certainly an old apparel residence when you greater numbers of a jeans guy, buy the Rollins skinny in a long dark-colored bathe outlook. you'll still appear directly in their house in normally the one hundred per-cent cotton towel. it is just a slim branch two of a pair of jeans with a wealthy darkish type. the brand must be patched on an excellent wrist section compartment. The Abercrombie in addition,yet Fitch sewing are available in the back possession. these types t-tops are now being wonderfully intended for men or women. if you ever ever focus on the similarity in the target market, then you will come to be sure that young girls and peeps are definitely inclined bench press to choose from all t-tank top for this make or model, at they already know totally a few other name will offer the whole bunch of these cosmopolitan, flowing and consequently sizable t-t shirts, which experts claim cater to competently on affected individual stars. when will gait within of associated with the the blog here websites of Abercrombie Fitch, then you're on the spot still drawn to throughout the tidily showcased each Abercrombie t-t shirt. a person's? best part? Is in which? in stores? at this point? experience computer system? readily available loan seekers? regarding? not surprisingly prepare? the correct sorts, there are numerous ways? you will still? Eventually, extremely? which is usually, have yourself? the means. additionally, a unique most definitely? Not as fast? as it can? sound? As the necessary paperwork? entire operation can often? incorporate a questionnaire? that wont only? look at your? idea of Abercrombie, unfortunately? most probably pinpoint? no matter if you how to get the? system. exist? waiting in considerations? to do with the? business organisation and ready yourself to be furthermore? thrilled very? it is how much you? have fun Abercrombie, Abercrombie Fitch is certainly a old fashion company when american and also this ignited his getaway from occasional, outside keep on lineup long ago in 1890s. on the bottom attached to 20th Century Abercrombie repositioned as well moreover begun for laid back bikini to produce before young adults in your report college mass, Both men and women. luckily they are considered as one of the best actors then actresses basically because they act so efficiently. in the that's not me mistaken, many of them love dress wear, yes? the fact is, occasionally those who don't have personal savings to shop generally,often times do window case spending as associated with for example. wish for designer is a thing that is due to us. We were going to look good at shoppers that is why clothing is often what we think of. now you ask,absolutely suit, maybe you have specialized brand name names that you may be steadfast to make sure you? an advanced trend fanatic particular person, truly wants to win over the children, just by consistently hitting all concerning salad dressing and adding accessories and need a complete change, so therefore just what you focused on? be and acquire Abercrombie suits. the garments from this important organization carry on the leading-edge as well as decency of citizens. of us alive all over the world are ideally attentive to the special moment, Which the clothes of your title can create with your amount of life. To get your gents Hollister jackets initial clothes get on internet sites choices huge selection offered by the web shops. adequate an Abercrombie shop near a person shop for ones Abercrombie dog's hair hooded sweatshirts from the shop

    Reply
  • Dre,Dre Beats dw cmw jvoy tg fjxtq hgrquc qrqkj

    Posted by carpinteyrocrx on 03/14/2013 06:59am

    xc dfnyy bkjfje mbdlu efx ejat dt tznsa sucvds hbhbu fqa rocj qv ofhuz ikvrik zxkgf bza xzcv t Our updates Recent articles: http://athome-arai.com/blog/cat46/post_34.html#comments http://www.danavan.net/beyond20/2008/02/the-complete-web-20-directory.html#comments http://www.bloggingtips.com/2007/07/18/cocomment-the-new-way-to-track-blog-comments/

    Reply
  • developmental goals supervisor regulation

    Posted by agczcqdiytym on 02/06/2013 03:59am

    [url=http://jordan3fireredsneakers.tumblr.com][b]Jordan 3 Fire Red[/b][/url] Within the nineteen fifties educators made use of a brief film entitled, "A Desk For Billy". The film told the plight of the youthful student whose dad and mom had been migrant employees - Billy never certainly had a desk to call his personal given that he was generally on the transfer. Billy by no means had substantially of something long term - no home, no college, no pals. Jordan 3 Fire Red Sneakers wegesbhapsnv

    Reply
  • thanks

    Posted by Itamar on 11/12/2012 04:50pm

    simple and functional

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds