Header background image for AlwaysMoveForward.com
Software

My MVC Experiment Part 9 Ajax

By Arthur Correa • Author

Something nice for the user experience.

What do I mean?  Well take the login section for example.  That little login section up above to the right gave me some problems.  How could I have an mvc submission for a login action, but still get sent back to the same view? 

My first thought was that I could just get the name of the current view and just return that from the controller action.  Nope, I couldn't find anything that gave me that information.

Now what?  Well the easiest thing is to just do an AJAX submission to just submit and refresh that section of the page.  Okay, MVC has some support for AJAX so lets look into doing that. 

 

 using (Ajax.Form("SendMail", new AjaxOptions { UpdateTargetId = "resultDiv" })) {    Your form elements here }

Pretty basic, define a form with some controls to submit via ajax and update a specific div with the return results.  Okay this sort of worked, but I actually wanted to have the form controls change after submission.  That is where it says "Your form elements here" I would start by having my input fields for the user id/password and the login button, but once logged in I wanted to change that to a greeting message and a logout button.

It would be even better if I could put my AJAX form right in my target div, that would let it play really nicely with a self contained control.  I could create a user control with a form defined in that would submit to a specific controller action.  

No problem, I got it working pretty easily, but I found my custom control wouldn't render when the page loaded.   The initial page render wouldn't cause the AJAX form to contact the server.  I had to force the page to submit the form when it loaded.  I had to add another chunk of javascript code to do an AJAX submission to draw the user control for the first time, and also add an ID attribute to the AJAX form so I could call it easily from javascript. 

Hmm I didn't like that, it felt clunky. Couple that with the fact that I just wasn't a fan of the ASP.NET MVC AJAX syntax (it felt more verbose than it needed to be) and I started to look for alternatives. Eventually I found this

Wow, this syntax was a lot nicer.  I could write the same HTML/ASP.Net code that I always did, normal forms, normal controls.  Just normal page processing.  Because of that I could easily create self contained user controls with normal HTML/ASP.Net page processing. 

All my ajax logic required was a couple of lines of a javascript project, and a div to contain my user controls.  Nice clean and simple.