This post covers a piece of functionality I’m always using, and just wanted a spot where I can do some quick copy/paste. There are a few pieces of functionality needed to make this happen, and the technology used, here are the assumptions about your environment:
- ASP.NET MVC 1.0
- jquery-1.3.2.js
- nHibernate (optional)
You can download the code sample here.
Preparing your controller to process the post
1. Create a method that returns a JsonResult like the one below:
public JsonResult AddContact(FormCollection f)
{
Contact c = new Contact();
//your logic for adding your object, be sure to include some error handling!
c.CreateAndFlush();
int NewID = c.ID;
//return the new key
return Json(NewID);
}
You would also have an Update method similar to the Add. For this example we will also add a delete method:
public JsonResult DeleteContact(int ID)
{
//for this example, i'm using nhibernate to handle crud statements
Contact c = Contact.Find(ID);
if(null != c)
{
c.Delete();
}
//in a real example there would be error handling
return Json("Ok");
}
Create a simple table and form
1. This example will have two fields: first and last name:
First, Last Name: <input type="text" name="firstname" id="firstname" />&nbsp; <input type="text" name="lastname" id="lastname" />&nbsp; <input type="button" onclick="Add();" value="add" />
2. Next we create a table to hold existing contacts, and then prepare it for adding/deleting:
<table width="100%" id="contactsTable">
<tr>
<th></th>
<th>Contact Name</th>
</tr>
<%
foreach(var item in Model)
{
//we need to add an id which uniquely ties this entire row to this contact for jQuery
Response.Write("<tr id='c" + item.ID + "'>");%>
<td align="left">
<a href="#" onclick="javascript:Update('<%= item.ID %>');">Update</a>&nbsp;&nbsp;
<a href="#" onclick="javascript:Remove('#c<%= item.ID %>','<%= item.ID %>');">Delete</a>
</td>
<td>
<%
string _firstnametext = "txtfirstname" + item.ID.ToString();
Response.Write(Html.TextBox(_firstnametext, item.FirstName));
%>
</td>
<td>
<%
string _lastnametext = "txtlastname" + item.ID.ToString();
Response.Write(Html.TextBox(_lastnametext, item.LastName));
%>
</td>
</tr>
<%}%>
</table>
In the above example, the data is displayed in textboxes for convenience. If you have many fields, you may want to use either a dialog (which will be covered in a future post) or redirecting the user to another page…but I digress. Now that we have our table ready, all we have left is creating the jQuery Add, Update, and Delete functions.
jQuery functions
So the last part is creating three simple calls using jquery to send changes back to the server. First is the most “complex” function, which is adding a new record. It is more complex because this will actually append the new contact to the table. As you’ll see, it isn’t rocket science:
function Add()
{
$.post("/Contact/AddContact", $("#Form1").serialize(),
function(data) {
//this function fires after the post;
//the data variable will have the new contact's pk value;
//this is a great spot to see if there was an error and adjust accordingly
var myObject = eval('(' + data + ')');
var ID = myObject;
var FirstName = $('#firstname').val();
var LastName = $('#lastname').val();
var Remove = '&nbsp;&nbsp;|&nbsp;&nbsp;<a href="#" onclick="javascript:Remove(\'#c' + ID+ '\',' + ID + ');">Delete</a>';
var NewRow = "<tr id='c" + ID+ "'>" +
"<td><a href='#' onclick='Update(" + ID + ")'>Update</a>" + Remove + "</td>" +
"<td><input type='text' name='txtfirstname" + ID + "' value='" + FirstName + "''></td>" +
"<td><input type='text' name='txtlastname" + ID + "' value='" + LastName + "''></td></tr>";
//this portion appends the new record to the table
$('#contactsTable tr:last').after(NewRow);
//clear out the add form
$('#firstname').val("")
$('#lastname').val("");
});
};
You can read more on form posting using jquery here: http://docs.jquery.com/Post. The next function is deleting a contact. Like all the examples in the post, you want to include your own logic for error handling!
function Remove(rowid,id) {
//the first line makes the request to delete the contact, the second line removes the row from the html table
$.post("/Contact/DeleteContact", { id: id});
$(rowid).remove();
}
Finally we have our Update call. This will be just like the Add function, except you don’t have to append a new row because the record is already there.
Hope you enjoyed!

Comments:2
Leave a Reply