Introduction
Many times when working with a parent child type UI, we want to show the details of child objects on
a modal popup fetched only on request (i.e., through AJAX).
And we might want to post form data using AJAX. Here is a simplified plug-in to help us post a form using AJAX and load the response in
a Modal dialog.
It also helps us to retrieve sub pages (or child details) in a modal dialog using AJAX.

(This project uses AJAX to post data and fetch returned values. The data is stored in an XML database using .NET XmlSerializer. This demo can be customized
to be used as a simple AJAX chatter with an XML database.)
Background
jQuery makes it easy to get and post data using AJAX. We do have many AJAX based modal popups. This article creates a simplified plug-in to achieve the same.
The emphasis is on simplifying fetching and posting of data using AJAX.
Running the demo
- Open the project as a website in Visual Studio. Open Index.htm. Build and
Run. or
- Host the contents of dmo.zip into a new website in your IIS configured as
an ASP.NET application.
Using the code
The first thing we need to do is include jQuery, jQuery-UI plug-in, and our AjaxLinks
plug-in in your page.
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="Styles/jquery.ui.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>
<script src="Scripts/AjaxLinks.js" type="text/javascript"></script>
Now to fetch a link into a modal popup through AJAX we should decorate that hyperlink with
the class="AjaxGet" attribute.
To post a form using AJAX we will need to decorate that form with
the class="AjaxPost" attribute.
Here is how the code works:
AjaxPostForm
Here is our AjaxPostForm function. This function attaches itself to the submit event of all the forms which
have been decorated with the class="AjaxPost" attribute. As explained in the comments below, this function:
- Attaches itself to the submit event of forms decorated with the
class="AjaxPost" attribute.
- Stops the normal posting of the form.
- Retrieves the target action of the form into a variable
url.
- Retrieves the values from the form and serializes them with help of the jQuery
$form.serialize() function.
- Performs AJAX POST using the jQuery AJAX function (
$.ajax(...)).
- If the result is successful, creates a modal dialog and displays the response
HTML of the target page.
- If the result is unsuccessful, creates a modal to show the error screen.
AjaxPostForm: function () {
$("form.AjaxPost").submit(function (event) {
event.preventDefault();
var $form = $(this);
var url = $form.attr('action');
var pdata = $form.serialize()
$.ajax({
type: "POST",
url: url,
data: pdata,
success: function (resp) {
var $jAlrtSuccess = $('<div />');
$jAlrtSuccess.html(resp);
$($jAlrtSuccess).dialog(AjaxLinks.postResponseDivParam);
},
error: function (xhr, status, error) {
var $jAlrtError = $('<div>' + xhr + '</div>');
$($jAlrtError).dialog(AjaxLinks.postResponseDivParam);
}
});
});
return false;
}
AjaxGetLink
And here is our AjaxGetLink function. This function attaches itself to the click event
of the hyperlinks decorated with the class="AjaxGet" attribute. As explained in the comments, this function:
- Attaches itself to the
click event of hyperlinks decorated with the class="AjaxGet" attribute
- Finds out the target of this link using the code and saves it in the variable
actionurl
- Sets up the width, height and position of the target modal popup which will
display as content, the HTML retrieved from the
actionurl
- Performs the Get operation using the jQuery AJAX function (
$.ajax(...))
- On success displays the response HTML into a modal dialog
- On error displays the error as a modal dialog
AjaxGetLink: function()
{
$('a.AjaxGet').click(function () {
var pdata = $(this).attr('data-value');
var $divNm = $('<div>Loading. Please wait....</div>').appendTo(
$(this)).dialog(); var actionurl = $(this).attr('href');
var horizontalCenter = Math.floor(screenWidth/2);
var verticalCener = Math.floor(screenHeight/2);
var myDialogX = 20;
var myDialogY = verticalCener-300;
var modalWidth = screenWidth -80;
var modalOptions = { height:600, width: modalWidth, autoOpen: true,
modal: true, zIndex: 3999, position: [myDialogX,myDialogY],
buttons: {Close: function() {$( this ).dialog( "close" );}} };
var dialogOpts = {
type: "GET",
url: actionurl+"?bustcache="+ new Date().getTime(),
data: pdata,
success: function (resp) {
$divNm.html(resp);
$divNm.dialog("destroy");
$divNm.dialog(modalOptions);
return false;
},
error: function (xhr, status, error) {
$divNm.html(xhr.responseText + status.toString());
$divNm.dialog("destroy");
$divNm.dialog(modalOptions);
return false;
}
};
$.ajax(dialogOpts);
return false;
});
},
Points of interest
For ASP.NET MVC we have quite a number of awesome helpers. If we want to make a form AJAX based, we can simply begin the form as Ajax.BeginForm() instead
of Html.BeginForm() and ASP.NET helpers will take care of generating the necessary AJAX code for us.
The XML persister class
Our persistence class, Persister is a cut down version of XML persister from My Web Pages StarterKit project.
This class can be useful for persisting your settings to XML config files. In our case, we are using it to persist our posts data into the XML
database (App_Data/Posts.config). It serializes and deserializes XML objects and abstracts a lot of functionality for you. All you need to do is:
- Provide the location of your XML file in the constructor.
- Provide the type of the object to persist in the XML.
public class Persister<T>
{
private string _dataFileName;
private List<T> _objList;
public List<T> objList
{
get { return (_objList); }
}
public Persister(string dataFileName)
{
this._dataFileName = HttpContext.Current.Server.MapPath(
string.Format("~/App_Data/{0}", dataFileName));
this._objList = Activator.CreateInstance<List<T>>();
}
public void save()
{
lock (_dataFileName)
{
using (FileStream writer = File.Create(_dataFileName))
{
XmlSerializer serializer = new XmlSerializer(_objList.GetType());
serializer.Serialize(writer, _objList);
}
}
}
public void load()
{
if (File.Exists(_dataFileName))
{
lock (_dataFileName)
{
using (FileStream reader = File.Open(_dataFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
_objList = (List<T>)serializer.Deserialize(reader);
}
}
}
else
{
_objList = new List<T>();
save();
}
}
}
Here is how we use it to persist our Posts objects:
Persister<Posts> currentPosts = new Persister<Posts>(_dataFileName);
currentPosts.load();
_posts = currentPosts.objList;
if (Request.RequestType == "POST")
{
string strName = Request.Form["txtName"];
Posts post = new Posts();
post.Name = strName;
_posts.Add(post);
currentPosts.save();
}
History
Initial post with introduction to AjaxGet Link and AjaxPost Form.
Programming is my hobby (and luckily my profession as well). My curiosity with computers started since early school days which inspired me to join computer hardware and even electronics repairs. The same interest made me choose Computer Science & Engineering as major in B.Tech. After a start with Java at college curriculum & teaching C programming for some time, I found the opportunity to work in C# and Asp.Net. I also like to study PHP, JSP-Struts and C etc. though my affair with Asp.Net, C# has been everlasting. I like to learn everything related to web - HTML, CSS, Javascript, JQuery and Photoshop etc.