I want to create a datatable that would be fetched via ajax (jsonresult) from the server (Action in mvc4). I want to add button to each row in each row (eg. View record) pertaining all the information of that row using jquery. Please help me out.
5 Answers
This will render a link in the column, you can obviously replace this or style it as a button.
In your table definition:
'aoColumns': [
{
'mRender': function (data, type, row) {
return "<a href='/View/" + row[1] + ">link</a>";
}
},
...
using row[i] you can access all the data in the current row. In my example, row[1] would be an id which is used to create a parameter passed to the 'View' action.
Comments
DataTable With Image (MVC)
<script src="~/Scripts/jquery-1.7.2.js" ></script>
<script src="~/Scripts/DataTables/jquery.dataTables.js" ></script>
<link rel="stylesheet" type="text/css" href="~/Content/DataTables/css/jquery.dataTables.css">
<script>
$(document).ready(function () {
$('#example').dataTable({
"processing": true, // control the processing indicator.
"serverSide": true, // recommended to use serverSide when data is more than 10000 rows for performance reasons
"info": true, // control table information display field
"stateSave": true, //restore table state on page reload,
"lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "All"]], // use the first inner array as the page length values and the second inner array as the displayed options
"ajax":{
"url": "@string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))/Home/AjaxGetJsonData",
"type": "GET"
},
"columns": [
{ "data": "Name", "orderable" : true },
{ "data": "Age", "orderable": false },
{ "data": "DoB", "orderable": true }, {
"render": function (data, type, full, meta) {
return '<img src="Content/'+full.Image+'">';
}
}
],
"order": [[0, "asc"]]
});
});
</script>
@*
using fiddler, the above generate the following request
http://localhost:57461//Home/AjaxGetJsonData?draw=1&columns[0][data]=Name&columns[0][name]=&columns[0][searchable]=true&columns[0][orderable]=true&columns[0][search][value]=&columns[0][search][regex]=false&columns[1][data]=Age&columns[1][name]=&columns[1][searchable]=true&columns[1][orderable]=true&columns[1][search][value]=&columns[1][search][regex]=false&columns[2][data]=DoB&columns[2][name]=&columns[2][searchable]=true&columns[2][orderable]=true&columns[2][search][value]=&columns[2][search][regex]=false&order[0][column]=0&order[0][dir]=asc&start=0&length=10&search[value]=&search[regex]=false&_=1437007829254
*@
<div style="margin:30px;">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr style="text-align:left;">
<th>Name</th>
<th>Age</th>
<th>DoB</th>
<th>Image</th>
</tr>
</thead>
<tfoot>
<tr style="text-align:left;">
<th>Name</th>
<th>Age</th>
<th>DoB</th>
<th>Image</th>
</tr>
</tfoot>
</table>
</div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace dataTableDemo.Controllers
{
public class HomeController : Controller
{
private const int TOTAL_ROWS = 995;
private static readonly List<DataItem> _data = CreateData();
public class DataItem
{
public string Name { get; set; }
public string Age { get; set; }
public string DoB { get; set; }
public string Image { get; set; }
}
public class DataTableData
{
public int draw { get; set; }
public int recordsTotal { get; set; }
public int recordsFiltered { get; set; }
public List<DataItem> data { get; set; }
}
// here we simulate data from a database table.
// !!!!DO NOT DO THIS IN REAL APPLICATION !!!!
private static List<DataItem> CreateData()
{
Random rnd = new Random();
List<DataItem> list = new List<DataItem>();
for (int i = 1; i <= TOTAL_ROWS; i++)
{
DataItem item = new DataItem();
item.Name = "Name_" + i.ToString().PadLeft(5, '0');
DateTime dob = new DateTime(1900 + rnd.Next(1, 100), rnd.Next(1, 13), rnd.Next(1, 28));
item.Age = ((DateTime.Now - dob).Days / 365).ToString();
item.DoB = dob.ToShortDateString();
item.Image = "images.jpg";
list.Add(item);
}
return list;
}
private int SortString(string s1, string s2, string sortDirection)
{
return sortDirection == "asc" ? s1.CompareTo(s2) : s2.CompareTo(s1);
}
private int SortInteger(string s1, string s2, string sortDirection)
{
int i1 = int.Parse(s1);
int i2 = int.Parse(s2);
return sortDirection == "asc" ? i1.CompareTo(i2) : i2.CompareTo(i1);
}
private int SortDateTime(string s1, string s2, string sortDirection)
{
DateTime d1 = DateTime.Parse(s1);
DateTime d2 = DateTime.Parse(s2);
return sortDirection == "asc" ? d1.CompareTo(d2) : d2.CompareTo(d1);
}
// here we simulate SQL search, sorting and paging operations
// !!!! DO NOT DO THIS IN REAL APPLICATION !!!!
private List<DataItem> FilterData(ref int recordFiltered, int start, int length, string search, int sortColumn, string sortDirection)
{
List<DataItem> list = new List<DataItem>();
if (search == null)
{
list = _data;
}
else
{
// simulate search
foreach (DataItem dataItem in _data)
{
if (dataItem.Name.ToUpper().Contains(search.ToUpper()) ||
dataItem.Age.ToString().Contains(search.ToUpper()) ||
dataItem.DoB.ToString().Contains(search.ToUpper()))
{
list.Add(dataItem);
}
}
}
// simulate sort
if (sortColumn == 0)
{// sort Name
list.Sort((x, y) => SortString(x.Name, y.Name, sortDirection));
}
else if (sortColumn == 1)
{// sort Age
list.Sort((x, y) => SortInteger(x.Age, y.Age, sortDirection));
}
else if (sortColumn == 2)
{ // sort DoB
list.Sort((x, y) => SortDateTime(x.DoB, y.DoB, sortDirection));
}
recordFiltered = list.Count;
// get just one page of data
list = list.GetRange(start, Math.Min(length, list.Count - start));
return list;
}
// this ajax function is called by the client for each draw of the information on the page (i.e. when paging, ordering, searching, etc.).
public ActionResult AjaxGetJsonData(int draw, int start, int length)
{
string search = Request.QueryString["search[value]"];
int sortColumn = -1;
string sortDirection = "asc";
if (length == -1)
{
length = TOTAL_ROWS;
}
// note: we only sort one column at a time
if (Request.QueryString["order[0][column]"] != null)
{
sortColumn = int.Parse(Request.QueryString["order[0][column]"]);
}
if (Request.QueryString["order[0][dir]"] != null)
{
sortDirection = Request.QueryString["order[0][dir]"];
}
DataTableData dataTableData = new DataTableData();
dataTableData.draw = draw;
dataTableData.recordsTotal = TOTAL_ROWS;
int recordsFiltered = 0;
dataTableData.data = FilterData(ref recordsFiltered, start, length, search, sortColumn, sortDirection);
dataTableData.recordsFiltered = recordsFiltered;
return Json(dataTableData, JsonRequestBehavior.AllowGet);
}
public ActionResult Index()
{
return View();
}
}
}
Comments
Just .. on while parsing / inserting you table via JSON/ajax...., call this function .. when you reach the needed cell (where you need the button) fn
function createBtn(){
var test = $('<button/>',{
text: 'Test',click: function () { alert('Do your button action'); }}
var parent = $('<tr><td></td></tr>').children().append(test).end();
$("#nodeTable tr:last").before(parent);
}
Try
