ASP.NET MVC Partial View and Ajax “real world” example

26 Apr

If you would like this sample code, right click here and “save as” to download. Then rename to a zip file and open.

In my previous post I have discussed and demonstrated how you can easily use jQuery and a ASP.NET MVC’s Partial View to accomplish an UpdatePanel-like solution. In this post I’d like to demonstrate a “real world” usage of this technique.

I wanted a cool looking Login dialog to popup on request when a user hits a simple “Log On” button, without having to refresh the entire page or redirecting the client to a Login page. In other words, there is no Login page, just a Login dialog. Naturally, I wanted this Log On button to be available across all the pages in the site. This could be easily be implemented using a layout (“Master Page”). But it’s more generic and nice to use a PartialView, to represent that button. More over, the basic code for this already exists in the MVC application template. Simply create a new MVC application and see for yourself. So there’s nothing new so far. However, the code for the login dialog is something new which is required and here I had basically 2 options:

  1. I could render the login dialog as a hidden dialog (“display:none”) in the Partial View (or layout). This is possible, will save a round trip to the server when the user requests to login, but is also quite “ugly” as it is inefficient to render a hidden dialog every time.
  2. I could have an UpdatePanel like implementation. Using a placeholder div, I could request another PartialView from the server on demand. The html rendered will be then “injected” into the placeholder div. I figure that this is way more efficient than the first option and can be considered, well, “nice”.

I decided to go with option 2. It felt more cool and correct, and also provided me with a great opportunity to practice this technique. Here’s the basics:

  1. We’ll create (or rather re-use MVC’s template code) a Partial View to represent a Log On/Log Off button. This will be rendered from the layout onto all pages. This view will also contain a place holder div, which will be injected with the log-in dialog.
  2. We’ll create a Partial View for the login dialog. This is basically a simple div which wraps the username/password textboxes. This will not be rendered anywhere at design time.
  3. We’ll use jQuery’s ‘load’ method to perform an Ajax call to the server, and return the Partial View of the log-in dialog. The dialog’s html will be injected into the place holder described in stage 1.
  4. We’ll create server side code to support the logon/logoff scenarios.

“Strategy”: The login button’s partial view is going to have a wrapping div, which will change according to the whether a user is logged in or not. This will be rendered at first according to the authenticity state, but will change at run-time according to the user’s operations. This will be described in 4 stages below.

Stage 1: Login button (Partial View). I reused MVC’s template code to do this. The entire code is wrapped with a div (‘divLoginButton’), whose contents will dynamically change according to Log on/log off operations performed by the user.

  • Line 1 is the wrapping div.
  • Line 2 is the server side code which decides whether a Log On or Log Off button will be rendered from the server.
  • Lines 4-9 represents a Log Off button. The user is logged in, authenticated, and has not requested to logoff (line 2 makes that decision).
  • Line 7 contains an Ajax call to actually perform the log off, and to replace the div’s entire content with a new state. This really resembles a Web Form’s UpdatePanel’s behavior, only cleaner and more efficient.
  • Lines 13-28 represent a situation that the user is not authenticated and a Log On button is displayed.
  • In line 17 we query whether the login dialog has already rendered from the server. This can happen if the user has clicked the Log On button, the dialog has rendered from the server (line 19), but has not logged in (e.g. clicked the Cancel button of the dialog). In this case, there’s no point in reloading the dialog from the server, so we reset the username/password fields (line 22) and reopen the dialog (line 25).
  • Lines 29-30 is the place holder for the login dialog.

Stage 2: Login dialog (Partial View). I created the new LoginDialog.cshtml PartialView file. This looks like this:

  • Lines 1-13 represent the “dialog”. This is just a basic div with username/password textboxes. This will be displayed as a modal dialog using jQuery UI’s Dialog. Because the dialog is set to autoopen, this will be automatically opened when rendered for the first time.
  • Lines 15-43 contains the JavaScript which will display the window as a dialog. If you’d rather have the JavaScript in a different JS file because you believe that rendering a JavaScript ajax response from the server is a bad thing, it’s also possible.
  • Line 23 indicates a POST ajax call. POST is done for security as I’d rather have the username/password (lines 25/26) not sent in the query string. The Ajax call is for the Login action method in the Home Controller.
  • Line 32 is executed when the result of the Login method is “Success”. This is what does the trick of replacing the “Log On” button with a “Log Off”, similar to the signout process discussed in Stage 1 above. It is possible to return the PartialView directly from the Login action (line 23), but I wanted to render a Success boolean in order to have more control, especially in case the Login fails.

Stage 3: Server side code to support the Log On / Log Off situations.

The comments are probably sufficient, but just in case:

  • Lines 15-18 return the Login Dialog partial view.
  • Lines 21-26 supports a Log Off scenario. Line 23 performs the actual Sign Out. Line 24 instructs the LoginButton partial view that although the user is still authenticated at this point, a Log On button should be rendered and not a Log Off button.
  • Lines 30-33 return a Log On or Log Off button, depending on the authenticity state of the user. Basically this is used after a successful login operation, when we would like to render a Log Off button.
  • Lines 36-42 represents a Login process. Line 38 should be replaced with actual Membership user login validation check. If true, line 40 sets the authentication cookie. Line 41 returns if a successful login was performed. As you can see, in this example the login is always a success.

Stage 4: Render the Login button in the layout (“Master Page”), so it’s visible throughout all the pages.

  • Line 11 represents the Login Button partial view (Log On / Log Off button).
  • Lines 5 and 8 are jQuery UI (required for the modal dialog).

Here’s how it looks. At first, the page is loaded and the Login button is rendered as a Log On button.

Now we click the Log On button. jQuery’s load method performs an Ajax request to the server, and the Login Dialog Partial View is rendered back. Because the JavaScript code which creates the dialog has an autoopen set to true, it automatically opens:

Now we type-in our credentials and click Login. A POST Ajax call to the server performs credential validation and returns a JSON with Success, meaning that the Login went ok and the user has logged in. Now another Ajax call takes place to “refresh” the state of the Login Button to that of a Log Off button. This looks like this:

Finally, when we click the Log Off button, another “refresh” takes place as the server’s LogOff button returns an updated Login Button.

That’s about it. As stated above, you could take the JavaScripts to a different JS file if you feel bad about rendering back JavaScript, or if you think that it’s more efficient either because the network load is reduced or because the JS file will be cached by the browser. It’s also possible to render both a Log On and a Log Off buttons at once and toggle their visibility on the client side, settling just for Ajax calls only to perform the credential validation and to set the cookies. In either case, this isn’t the point of this blog post. The point is to show multiple examples of Partial Views used as Web Forms Update Panels, using jQuery.


Posted by on 26/04/2011 in Software Development


Tags: , , , , ,

124 responses to “ASP.NET MVC Partial View and Ajax “real world” example

  1. Benjamin

    31/05/2011 at 21:18

    Could you just use an inserted partial view instead of the popup dialog? How would that change the jquery code, please? You tutorial is the closest thing to helpful I can find, but I just don’t know how it works with a cshtml file instead of a modal dialog.

    • evolpin

      01/06/2011 at 01:48

      Hi Benjamin,

      Please note that the popup dialog is within LoginDialog.cshtml, meaning, it is a cshtml. The fact that this example renders a JavaScript code which generates a dialog doesn’t mean that you can’t use it to render any html of your choice. In other words, jQuery’s load will remain the same, and the server side Action method will simply return html embedded within your cshtml. Just make sure that when you add a new view, you check the “Create as partial view”. Check out this post which I believe demonstrates what you’re asking for:

      I hope this helps.

  2. amitpatelit

    12/07/2011 at 15:02

    How can we handle validation over here.

    • evolpin

      12/07/2011 at 20:43

      Not sure exactly which validation you are referring to, but assuming that you’re referring to client validation, you can validate prior to posting the username/password.

  3. Xavi Rodà

    20/07/2011 at 13:46

    Thank you for sharing. It’s one of the best MVC tutorials because you talk about real things. All the MVC stuff that you can find in he web are extremely simplified examples that make no sense in real applications.

  4. sai

    20/11/2011 at 22:05

    It looks great. can you send the source code of the app. I had some problem after following the steps.
    I had the latest jquery plugin. I dont think that might be causing the issues. Thanks in advance.

    • evolpin

      21/11/2011 at 20:28

      Hi sai,

      I have sent you the code via email.
      Good luck.

      • Tony

        06/01/2012 at 18:03

        Can you send me it also please?

      • evolpin

        06/01/2012 at 22:27

        Sent to you as well. Good luck.

    • med

      03/04/2014 at 23:17

      can u send the code please i need it thank u

  5. sun

    23/12/2011 at 12:56

    Nice example but not working on clicking LogOn it does appears popup but no login action is working

  6. Yogesh

    19/01/2012 at 16:11

    Awesome example……….can you please send the same on

    • evolpin

      19/01/2012 at 18:31

      Thanks for your complements.
      The example was sent to you.

  7. samhtc

    25/01/2012 at 23:15

    Could you please show an example on how to send an email through a modal popup window (using jquery) in an mvc application

    • evolpin

      26/01/2012 at 20:42

      Please refer to this post on how to use jQuery to activate Actions on the server. Then you can use .NET’s libraries for sending emails. Here is a good example and web site explaining this.

  8. Hasan Nazeer

    28/01/2012 at 00:24

    awsome tutorial. can I get a copy of the code?

  9. Max

    30/01/2012 at 16:15

    Hi. Thanks for tutorial. Can you send me code?

  10. Tung Nguyen

    31/01/2012 at 07:08

    It looks great, can you send this code to me:

    Thank you so much.

  11. Rama Kanth

    12/02/2012 at 21:32

    Nice Job. IT would be nice if you can post the code to my mail id or in the site itself … that would be helpfull

  12. Ben

    16/02/2012 at 16:34

    Would like to try this, could you send the code? Thanks for explaining.


    21/02/2012 at 03:30

    good example..can you please send this code to me blessings

  14. Ameet

    21/02/2012 at 08:23


    Can you please send the code at

  15. caglar

    24/02/2012 at 15:05

    please send this code to me

  16. pic

    02/03/2012 at 10:47

    Great, I’m looking for that. Can you please send the same on

  17. lmagruder

    24/03/2012 at 21:04

    Thanks for a tutorial where you take the time to explain how the pieces fit together and why you made certain decisions. I saw a lot of people asking for code, you know that wordpress lets you use that tag

     blah blah blah 

    ? I know you probably knew that, and I think it’s a good thing when learning to type in code when it’s small enough … just mentioning it on the off chance you didn’t know.

    Anyway, when I run it, for some reason I successfully get the login prompt “injected” into my div ajaxishly, but the script that is part of the partial view doesn’t make it to the page. I only get the html up to the closing div, the script that calls js-UI ‘dialog’ doesn’t make it into the view. On the other hand, if I go directly to the url mysite/home/OpenLogin, the javascript is all there fine. Is there any configuration related to whether a server will send back javascript blocks in an ajax request that I should know about? (Realizing I’ll probably have found the answer and moved on by the time you see this, but maybe something to add in for future reasons if it’s a common newbie issue)

    Thanks again

    • evolpin

      26/03/2012 at 22:35


      Thanks for your feedback.
      As for your comments about the code: I have written several blog posts using different code alternatives: Code4Blog, who looked promising at first; “Scott Gu”‘s style of screenshots (as in this blog) and my recent posts used WordPress’ sourcecode as you mentioned. The reason I did not want sourcecode at first was because it’s highlighting did not match Visual Studio. However, because Code4Blog required too many adjustments, and the screenshots do not allow copying the code, I decided to use it for now, unless a better alternative came along.

  18. lmagruder

    24/03/2012 at 21:06

    arg in comment i just left I guess I had to escape the wordpress tags, I wasn’t expectig that, I meant to say “left square bracket sourcecode language = “javascript” right square bracket”

  19. lmagruder

    24/03/2012 at 22:47

    Okay, never mind on the question about why stuff doesn’t render, it turned out to be a dumb mistake in setting up the Url.Content links to javascript that was giving me problems. But I learned a lot hunting it down. Thanks again for the tutorial

  20. anonymous

    04/04/2012 at 17:23

    can anyone please send this code to me too

  21. vivi

    04/04/2012 at 22:25

    Hi Marc,
    That’ s the great tutorial that you make there.

    Can you sent me the source code please ?

    Thanks a lot

  22. Rahul Vala

    07/04/2012 at 20:44

    Nice example.. found exactly what i wanted.. can you send the source code please?

  23. Santosh Patil

    09/04/2012 at 07:52

    can u send me copy of code at

  24. sheir

    09/04/2012 at 20:58

    I am new to MVC3+Razor and wondering if a main view can use more than one partial views where some partials are a Form (ie Html.BeginForm() or Ajax.BeginForm()) and each has its own model
    (ie one partial has Settings as its model class while another partial has JobStatus as its model class).
    Is that possible?

    Also what is the difference between the Html and Ajax BeginForms??

    And would you be able to send me your sample code (


    • evolpin

      10/04/2012 at 19:37

      – Although I did not try it, I guess that there’s no reason why you can’t use multiple form tags in MVC (unliked WebForms).
      – Basically you can also use several Model types per Partial View and the Main. Again, I did not try this except for a simple test project, but I guess that it should be possible to use this alongside with different form tags.
      – Html forms perform full postback where as Ajax forms do not. Perhaps you should read this post as well.
      – Sent you the code.

  25. QuynhNguyen

    23/04/2012 at 09:54

    Very helpful article!. Please send me source code to me via Thank in advance!

  26. Ev Olpin

    23/04/2012 at 20:59

    Dude, I’m unable re-create your technique. Can you shoot me your source code to my mail address? Merci beaucoup.

  27. Roy W Bradley

    27/04/2012 at 16:32

    Would you please forward the source code for this article. Thank you…

  28. Sun Kathiravan

    10/05/2012 at 11:30

    please send an email this code to me…

  29. Khurram

    22/05/2012 at 14:56

    awesome it really well. can you send me the code please.

  30. cat

    31/05/2012 at 08:45

    good example..can you please send this code to

  31. Esteban

    07/06/2012 at 07:19

    please send an email this code to me…

  32. don

    09/06/2012 at 18:06

    Hi, Please help me share source code:

  33. anupam

    11/06/2012 at 20:53

    awsome tutorial. can I get a copy of the code?

    • Tom

      27/06/2012 at 15:28

      that is full copy of the code already, what more do you want? don’t ask for a zip. type it up yourself, only takes 5 minutes.

  34. Tom

    27/06/2012 at 15:11

    in the first piece of code (first picture) $(‘#dlgLogin”).dialog(‘open’); //reopen previously rendered, use $(‘#dlgLogin”).dialog().show(); instead. Because you may have a good chance to use show:{effect:…} with dialog later on, .dialog(‘open’) will not hit the effect code, but .show() will do the same job as .dialog(‘open’) plus rendering effects. It is very strange, the method .show() is not even in dialog’s API !!!

  35. Tom

    27/06/2012 at 15:18

    By the way, this article is an execllent start, but is not a complete ‘real world’ example. If you work thru this tutorial, you will not get to the login box as shown (2nd last picture), not yet anyway. you are still about 50% coding away from it.
    If you want to achieve something like that (2nd last picture) best bet is to check out JQuery UI ThemeRoller. Download the ThemeRoller package, and learn how to get there to render a ‘real’ JQuery Dialog by studying the source code in its demo folder.

  36. Tom

    27/06/2012 at 15:26

    Also, in the 3rd piece of code (3rd picture). //perform login Public ActionResult Login(string username, string password) … use Public ActionResult Login(LogOnModel model) to be more MVC-style. The model binder in MVC framework is smart enough to match up {username, password, rememberme…} into the strongly typed LogOnModel, case-insenstively! Good eh?

  37. Tom

    27/06/2012 at 15:32

    Do not ask the author to send you a piece of code. This tutorial is OP-ly defailed already. I would like to tell you people to read the code and type it up yourself. The author bothered to write this kickass tutorial, you need to at least be respectful enough to use your eye balls and fingers to copy it the good old fashion way.

  38. Sana

    12/07/2012 at 06:42

    I want to have different menus in my project with repect to the usertype of the user that logs in, How can i achieve it in mvc3. In I did same thing by placing a place holder in master page and the creating differnt .ascx file for three different user type. then in masterpage code behind i user if condition and checked the user type and the loaded the required ascx user controlls to didplay the menus. Bt in ASP.NET MVC3 am not able to make any such things. I am very new to mvc so please help me..
    If possible do send me reply in



  39. Hailman

    21/07/2012 at 02:37


    Can you please send the source code to me? hooman198@gmail dot com


  40. Sudheer

    09/08/2012 at 08:12

    very good articel…can u send me the code to

  41. Manojit Mondal

    25/08/2012 at 18:37

    I am looking this type of feature on my application. can you send me the source code to

  42. lucas braca

    29/08/2012 at 01:39

    Ejemplo impresionante ………. puede usted por favor enviar el mismo en

  43. lucas braca

    29/08/2012 at 02:33

    please send an email this code to me…

  44. lucas braca

    29/08/2012 at 02:34

    please send an email this code to me…

  45. Steveluong

    29/08/2012 at 20:18

    could you send me the code to

    really appreciate!

  46. D33Funky

    11/09/2012 at 22:52

    Great article!
    In case of Forms Authentication a Login URL is provided in web.config to automatically redirect unauthorized requests to this URL with ReturlUrl parameter added. Is there a way we can provide such login URL and use the technique described in this article and automatically open login popup to unauthorized requests? Thanks in advance!

    • evolpin

      13/09/2012 at 08:35

      I assume that you could provide such a service, but this probably depends on the technique that you use for authorization. For example, you could try to inherit and implement a custom AuthorizeAttribute ( that upon failure returns a response that the client interprets and opens the login popup. Didn’t try it myself, but it’s something worth looking into.

      • Marrou

        15/09/2012 at 22:32

        Great example and very nice explanation.
        Would you please send me the code as well ?

      • Daniel

        05/04/2013 at 15:17

        Have you ever gave it a try?, I couldn’t find a good way to make it work with FormsAuthentication.

  47. vikas

    18/09/2012 at 13:03

    could you send me the code to

    really appreciate!

  48. R

    19/09/2012 at 16:40

    Plz Send me the code

  49. Manusama, Bram

    04/10/2012 at 04:17

    I really would like to learn more, can you please send the code to: Thanks

  50. albertiniolivier

    17/10/2012 at 23:58

    Great !! It’s exatly what i want … Can i have the code ??

    Thank you so much !!!!!

  51. Jackson

    25/10/2012 at 05:31

    Nice example. Can you send me the code please? Thanks.

  52. Rahul K

    06/11/2012 at 06:07

    Nice example, Can you send me code?

  53. Pedro Rebelo

    06/11/2012 at 12:43

    Hi. Nice example, can you send me the code?
    Thanks a lot 🙂

  54. yimihowmihow

    05/02/2013 at 14:01

    Hi evolpin, congratulations, this is a really good example!. Could you send me the code by email? Thanks in advance!

  55. sujata

    06/02/2013 at 12:38

    Hi Sir,

    Could you share this code plz?

    • sujata

      06/02/2013 at 12:39

      Hi Sir,,
      this realy good example.could you send me the code by email plz?


      • evolpin

        06/02/2013 at 21:47

        @yimihowmihow and @sujata.
        The code is available and shared. Just read the instructions in the top of the post on how to download it.

  56. vijay

    14/02/2013 at 12:07

    is it possible we can implement the both login and registration view using above example .

    i was try from last two days is not possible for me if u having sample code for that plz if possible then send on my personal mail id

    • evolpin

      15/02/2013 at 21:41

      Well, yes. You can do just about whatever you want. Simply create the relevant partial views and load them as shown in the example, one at a time according to what you need.

  57. Omar

    16/02/2013 at 11:51

    Could you please send this code to me as I want to do like this

    • evolpin

      17/02/2013 at 09:52

      kindly read the instructions at the top of the post on how to download the example

  58. Avinash

    17/04/2013 at 19:49

    hi..I have implemented the solution n it work great..but then i come across a problem that i cnt find a solution..i am localising my url..Therefore we can have /fr/home/index or /en/home/index.. the popup stop working when the url work only with /home/index. Any help will be much appreciated

  59. Patrick

    25/04/2013 at 20:51

    The link to download the code is broken. I would love the example

    • evolpin

      26/04/2013 at 16:20

      make sure that you right-click and save as described

      • pwensel

        26/04/2013 at 16:27

        Didn’t work in Chrome, did it in IE and it was fine…. I hate web development! I love web development! I hate web development! I love web development! I hate web development! I love web development!

      • evolpin

        26/04/2013 at 16:47

        I just tested it in Chrome and it works.

  60. Rafiq Ahmed

    07/05/2013 at 21:08

    Nice Example.. Please send the code

  61. jalal

    03/06/2013 at 08:22

    i think this is a perfect and effective example…….thanks for sharing.

  62. ctthang

    08/06/2013 at 16:24

    Great example! However you should render the LoginDialog partial view for the first load and set autoOpen: false. By that way the login dialog is showed faster whenever user click on Login link.

  63. R

    11/06/2013 at 18:18

    Hi, Can you please send me code as well, thnx!

  64. R

    11/06/2013 at 23:28

    link for download is not working

  65. Imran

    13/06/2013 at 14:59

    Hi, please …please Can you please send me code as well …i am needing it urgently my id

    • evolpin

      13/06/2013 at 15:15

      please read carefully the instructions at the top of the post on how to download this code.

  66. NeedYourCode

    13/06/2013 at 15:28

    download link not working ….can you do something for that thanks

    • evolpin

      13/06/2013 at 17:43

      the download link is working. read carefully what you have to do in order to download.

  67. josh

    05/07/2013 at 14:29

    good example.I found another good example in this link

  68. Krish

    02/08/2013 at 08:42

    Nice Articel, Can you send me the source code to

  69. Faisal Bashir

    20/08/2013 at 00:26

    Hi, can someone send me source code to

  70. Imran

    09/09/2013 at 11:04

    Its so nice and helful article relating partial view using Ajax postback. I tried this technique but having some problems. Kindly send me its source code as a running project. Thanx

  71. yasin

    04/01/2014 at 15:37

    example mail adres sender thankyou

  72. Noor

    21/01/2014 at 08:47

    Thaks for sharing please send me the Code sample to my email address

  73. Azad

    10/02/2014 at 12:28

    Can you please send the code on my :

  74. Edison Costa

    21/02/2014 at 16:45

    Great article. Can you send me it also please? Thanks a lot my e-mail is

  75. Varsha Panjwani

    27/02/2014 at 15:10

    awesome example can you plz send me a copy

  76. albertiniolivier

    16/03/2014 at 16:42

    Good post, good explanation ! Very clear ! I created a tutorial with ajax and partial view. I explain how to automated the result of controller depending of the context. For that, i use ControllerActionInvoker. there is an demo ! It’ s a good next step after yours.

    here the link :

  77. med

    03/04/2014 at 22:57

    very good article ..send me the code please to
    thank u .

  78. Aditya Goel

    10/07/2014 at 14:33

    excellent article.. could you please send me the code at

  79. Purna

    10/07/2014 at 20:41

    Hello, this is a great article. Could you send code to
    Thanks very much

  80. Raul

    25/07/2014 at 00:44

    Hi! Very nice article! Could You please send source code? L2AUL@HOTMAIL.COM

  81. gfd

    27/08/2014 at 18:23

    Why not just provide a download for the code in the article, instead of people having to ask for it.???

    • evolpin

      27/08/2014 at 19:00

      Not sure why the shouting. An example is available for download if you follow the instructions specified at the beginning of the article. As WordPress does not allow upload of zip files I had to rename it to a jpg, so you have to rename it back.

  82. Tuan Le

    15/12/2014 at 02:12

    Would you please email the source code: tuan…

  83. Mazhar

    21/05/2015 at 11:50

    please email the source code

  84. Swati

    09/06/2015 at 06:32

    can u please send me code

  85. panadchinmayee

    02/07/2015 at 14:54

    Thanks for the idea.
    Plz make it available to download atleast.How can we learn from you if we can’t try it.

  86. albertiniolivier

    03/07/2015 at 01:46

  87. ramnath

    14/03/2016 at 23:39

    can you please send to this mail id

  88. neeraj

    12/10/2017 at 11:38

    Awesome ……….can you please send the same on


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: