使用jquery数据表向每行添加按钮

时间:2014-06-18 13:27:12

标签: jquery asp.net-mvc-4 datatables

我想创建一个可以通过ajax(jsonresult)从服务器获取的数据表(mvc4中的Action)。我想为每行中的每一行添加按钮(例如,查看记录),使用jquery来关联该行的所有信息。请帮帮我。

5 个答案:

答案 0 :(得分:1)

这将在列中呈现一个链接,显然可以替换它或将其设置为按钮。

在您的表定义中:

'aoColumns': [
{
    'mRender': function (data, type, row) {
                        return "<a href='/View/" + row[1] + ">link</a>";
                    }
},
...

使用row [i]可以访问当前行中的所有数据。在我的示例中,row [1]将是一个id,用于创建传递给&#39; View&#39;动作。

答案 1 :(得分:1)

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();
            }

        }
    }

enter image description here

答案 2 :(得分:0)

只需..在通过JSON / ajax解析/插入表时...,调用此函数..当你到达所需的单元格(你需要按钮的地方)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);
}

尝试

答案 3 :(得分:0)

您可以使用fnDrawCallback函数在每行添加按钮

fnDrawCallback:function(){
    $('.tableClass tbody').find('tr').each(function(i){
          $(this).append('<a href="link'+i+'" >Button '+i+'</a>')

     });

}

答案 4 :(得分:0)

这应该有用。

 "aoColumns": [

                 {

       "fnRender": function (oObj)
         {
             return "<button type="button" onclick="buttonaction();">MyButton</button>
         }             


                 }]