Tablesorter append data from AJAX,but tablesorterPager size fail - ajax

Tablesorter version: 2.22.3
I used the AJAX Get data from Server side,but finally the table row always 10.
P.S. tablesorterPager size property already set 9999
The table row will display all the data.
HTML and JS is
$(function () {
var gv_table;
gv_table= $("#Info").tablesorter({
theme: 'blue',
sortList: [[0, 0]],
widthFixed: true,
widgets: ['zebra', 'columnSelector', 'stickyHeaders'],
widgetOptions: {
columnSelector_container: '#ColumnSel',
columnSelector_columns: {
},
}
})
.tablesorterPager({
// target the pager markup - see the HTML block below
container: $("#infopager"),
size: 9999,
output: 'Showing: {startRow} to {endRow} (Total:{totalRows})'
});
});
$('#btnQuery').click(function () {
$.ajax({
url: "../Handler/DataSrcHandler.ashx?TableName=UserInfo",
type: 'POST',
data: {
DataSrc: $("#SelEnviro").val(),
Datakey: $("#txtUserKey").val()
},
success: function (response) {
$('#info tbody').empty().append(response);
$('#info').trigger('update');
}
});
};
<div id="infopager" class="pager" style="width:180px">
<span style="width:180px;color:blue" class="pagedisplay"></span>
</div>
<div style="overflow:auto;width: 500px;height:150px" >
<table id="Info" class="tablesorter">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Sex</th>
<th>Address</th>
<th>Class</th>
<th>EngName</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
</div>
ashx return message is like
<tr>
<td align='center' valign='top' nowrap>Peter</td>
<td align='center' valign='top' nowrap>0123456789</td>
<td align='center' valign='top' nowrap>Boy</td>
<td align='center' valign='top' nowrap>NA</td>
<td align='center' valign='top' nowrap>A</td>
<td align='center' valign='top' nowrap>Peter</td>
</tr>

Related

Sort table using jquery.ui and store the new position to database

I have a table named categories where I store the categories for an E-Commerce. This table has the following aspect:
And this is the user interface to admin the categories.
I want to make a system to sort this table using JQuery.UI.
This is what I tried, but it returns me 500 (Internal Server Error)
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col" span="1">Nombre</th>
<th scope="col" span="1" class="table-justified hide-mobile">Estado</th>
<th scope="col" span="1" class="table-opts">Orden</th>
<th scope="col" span="1"></th>
</tr>
</thead>
<tbody id="table_content">
foreach($categories as $category)
<tr data-index="{{$category->id}}" data-position="{{$category->position}}">
<td class="table-text">{{$category->name}}</td>
<td class="table-text table-justified hide-mobile">
if ($category->visibility)
<i class="far fa-eye"></i>
else
<i class="far fa-eye-slash"></i>
endif
</td>
<td class="table-text table-opts">{{$category->position}}</td>
<td class="table-opts">
<div class="operations">
<a href="{{url('/admin/categories/'.$category->id.'/edit')}}" class="btn-edit pV-8 pH-12" data-bs-toggle="tooltip" data-bs-placement="top" title="Editar">
<i class="fas fa-edit"></i>
</a>
<a href="{{url('/admin/categories/'.$category->id.'/delete')}}" class="btn-delete btn-confirm pV-8 pH-12" data-bs-toggle="tooltip" data-bs-placement="top" title="Eliminar">
<i class="fas fa-trash-alt"></i>
</a>
</div>
</td>
</tr>
endforeach
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function(){
$('#table_content').sortable({
cancel: 'thead',
stop: () => {
var items = $('#table_content').sortable('toArray', {attribute: 'data-index'});
var ids = $.grep(items, (item) => item !== "");
$.post('{{ url('/admin/categories_list/reorder') }}', {
": $("meta[name='csrf-token']").attr("content"),
ids
})
.fail(function (response) {
alert('Error occured while sending reorder request');
location.reload();
});
}
});
});
</script>
And this is the controller function:
public function postCategoriesReorder(Request $request){
$request->validate([
'ids' => 'required|array',
'ids.*' => 'integer',
]);
foreach ($request->ids as $index => $id){
DB::table('categories')->where('id', $id)->update(['position' => $index+1]);
}
return response(null, Response::HTTP_NO_CONTENT);
}
Consider the following example.
var tableData = [{
id: 1,
name: "Cat 1",
visibility: true,
position: 1
}, {
id: 2,
name: "Cat 2",
visibility: false,
position: 2
}, {
id: 3,
name: "Cat 3",
visibility: true,
position: 3
}, {
id: 4,
name: "Cat 4",
visibility: true,
position: 4
}, {
id: 5,
name: "Cat 5",
visibility: true,
position: 5
}];
$(function() {
function updateTable(data) {
$.each(data, function(i, r) {
var row = $("<tr>", {
"data-index": r.id
}).data("row", r).appendTo("#table_content");
$("<td>", {
class: "table-text"
}).html(r.name).appendTo(row);
$("<td>", {
class: "table-text table-justified hide-mobile"
}).html("<i class='fas fa-eye'></i>").appendTo(row);
if (!r.visibility) {
$(".fa-eye", row).toggleClass("fa-eye fa-eye-slash");
}
$("<td>", {
class: "table-text table-opts"
}).html(r.position).appendTo(row);
$("<td>", {
class: "table-opts"
}).appendTo(row);
$("<div>", {
class: "operations"
}).appendTo($("td:last", row));
$("<a>", {
href: "/admin/categories/" + r.id + "/edit",
class: "btn-edit pV-8 pH-12",
title: "Editor",
"bs-toggle": "tooltip",
"bs-placement": "top"
}).html("<i class='fas fa-edit'></i>").appendTo($("td:last > div", row));
$("<a>", {
href: "/admin/categories/" + r.id + "/delete",
class: "btn-delete btn-confirm pV-8 pH-12",
title: "Eliminar",
"bs-toggle": "tooltip",
"bs-placement": "top"
}).html("<i class='fas fa-trash-alt'></i>").appendTo($("td:last > div", row));
});
}
function gatherData(table) {
var rows = $("tbody > tr", table);
var item;
var results = [];
rows.each(function(i, el) {
item = $(el).data("row");
item.position = i + 1;
results.push(item);
});
return results;
}
updateTable(tableData);
$('#table_content').sortable({
cancel: 'thead',
start: (e, ui) => {
start = $('#table_content').sortable('toArray', {
attribute: 'data-index'
});
},
stop: () => {
ids = gatherData("table");
console.log(start, ids);
/*
$.post('/admin/categories_list/reorder', {
"csrf-token": $("meta[name = 'csrf-token']").attr("content"),
ids
})
.fail(function(response) {
alert('Error occured while sending reorder request');
location.reload();
});
*/
}
});
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#fortawesome/fontawesome-free#5.15.4/css/fontawesome.min.css" integrity="sha384-jLKHWM3JRmfMU0A5x5AkjWkw/EYfGUAGagvnfryNV3F9VqM98XiIH7VBGVoxVSc7" crossorigin="anonymous">
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col" span="1">Nombre</th>
<th scope="col" span="1" class="table-justified hide-mobile">Estado</th>
<th scope="col" span="1" class="table-opts">Orden</th>
<th scope="col" span="1"></th>
</tr>
</thead>
<tbody id="table_content">
</tbody>
</table>
This should allow you to pass the new position for each ID to the script so the Database is updated.

laravel vue send array to backend

I want to send array of id's to backend with one button from vuejs table but i get error 500.
Logic
Check the check boxes
Collect the id's
Send id's to back-end when click on button
update the view
Code
template
<table class="table table-dark table-hover table-bordered table-striped">
<thead>
<tr>
<th class="text-center" width="50">
//the button
<button class="btn btn-outline-danger" #click="withdraw(index)">Withdraw</button>
</th>
<th class="text-center" width="50">#</th>
<th class="text-center">Amount</th>
</tr>
</thead>
<tbody>
<tr v-for="(income,index) in incomes" v-bind:key="index">
<td class="text-center">
//check box input
<input v-if="income.withdraw == '0'" type="checkbox" :id="income.id" :value="income.amount" v-model="checkedNumbers">
</td>
<td class="text-center">{{index+1}}</td>
<td class="text-center">Rp. {{formatPrice(income.amount)}}</td>
</tr>
<tr>
<td colspan="2"></td>
<td>
<span>Withdraw for today, Sum: <br> Rp. {{ formatPrice(sum) }}</span>
</td>
</tr>
</tbody>
</table>
script
export default {
data() {
return {
incomes: [],
checkedNumbers: [],
}
},
computed: {
sum() {
return this.checkedNumbers.reduce(function (a, b) {
return parseInt(a) + parseInt(b);
}, 0);
}
},
methods: {
withdraw(index) {
let checkedids = this.incomes[index]
axios.post(`/api/withdrawbutton/`+checkedids).then(response => {
this.income[index].withdraw = '1'
this.$forceUpdate()
});
}
}
}
route
Route::post('withdrawbutton/{id}', 'IncomeController#withdrawbutton');
controller
public function withdrawbutton($id)
{
$dowithdraw = Income::where('id', $id)->get();
$dowithdraw->withdraw = '1';
$dowithdraw->save();
return response()->json($dowithdraw,200);
}
Any idea where is my mistake and how to fix it?
......................................................................................................................
Don't send the list as a GET parameter, send it as a POST:
let params = {}
params.ids = this.checkedNumbers
axios.post(`/api/withdrawbutton/`, params)
.then(response => {
this.income[index].withdraw = '1'
this.$forceUpdate()
});
Controller
public function withdrawbutton(Request $request)
{
$dowithdraws = Income::whereIn('id', $request->input('ids', []));
$dowithdraws->update(['withdraw' => '1']);
return response()->json($dowithdraws->get(), 200);
}
Route
Route::post('withdrawbutton/', 'IncomeController#withdrawbutton');
And I don't think you need to update anything in the front because you already have them checked (if you want to keep them checked)

DataTables not working - Ignited Datatable Library

I have used ignited datable to integrate it in codeigniter but getting following error : DataTables warning: table id=example2 - Requested unknown parameter '0' for row 0.
$(document).ready(function() {
$('#example2').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sServerMethod": "POST",
"sAjaxSource": "<?php echo base_url()?>auth/datatable"
} );
} );
Here is my html
<table id="example2" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Class</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
here is the json generated
{"draw":0,"recordsTotal":2,"recordsFiltered":2,"data":[{"email":"admin#admin.com","first_name":"Admin","last_name":"istrator"},{"email":"subhadeepgayen#gmail.com","first_name":"Subhadeep","last_name":"Gayen"}]}
can seem to find any solution :(
Hello you need only specify the columns
"columns": [
{ "data": "id" },
{ "data": "name" }
]
Have you tried this - http://ellislab.com/forums/viewthread/160896/
And also this - http://www.ahmed-samy.com/php-codeigniter-full-featrued-jquery-datatables-part-1/
Do let me know if you succeed.
Best

How to expand all drill down rows while loading a datatable, including the hidden rows

I'm working on creating a datatable that has a drill down (row details) sub datatable as per the requirement. I was able to create the sub datatable when using drill down (row details) approach, but finding it hard to expand all of these rows that have drill down associated while loading the table. Here is the code I have and it works and expands all drill down rows on the current paginated table., but when clicking on the next pagination (number or page), the rows shows as expand (you know you can see the 'minus' (close) icon image) but no sub datatable. As far as I understood, its because, when I'm trying to simulate a click on the 'img' attribute associated for a drill down row, its being applied successfully for the current rows in the current page, but for the rest, which are not in the dom, the script says that the sub datatable is undefined. Any ideas or suggestions around this would help me a lot..
Below is the code snippet -
Table HTML source code -
<table id="mastertable" class="table table-striped table-bordered table-hover dataTable" aria-describedby="sample-table-2_info">
<thead>
<tr role="row">
<!-- <th class="sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" aria-label="Domain: activate to sort column ascending" style="width: 255px;"></th> -->
<th class="sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" aria-label="Domain: activate to sort column ascending" style="width: 25%;">Project Name</th>
<th class="sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" aria-label="Price: activate to sort column ascending" style="width: 10%;">Status</th>
<th class="hidden-480 sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" aria-label="Clicks: activate to sort column ascending" style="width: 10%;">Start Date</th>
<th class="hidden-480 sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" aria-label="Clicks: activate to sort column ascending" style="width: 10%;">End Date</th>
<th class="hidden-480 sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" aria-label="Clicks: activate to sort column ascending" style="width: 10%;">FCS Date</th>
<th class="hidden-480 sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" aria-label="Clicks: activate to sort column ascending" style="width: 10%;">Project Phase</th>
<th class="hidden-480 sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" aria-label="Clicks: activate to sort column ascending" style="width: 15%;">Defects</th>
</tr>
</thead>
<tbody role="alert" aria-live="polite" aria-relevant="all">
<tr>
<td class=" ">
<img src="/tester/theme/v_1_0/app-images/details_open.png" masterProject="master-ROORKELA"/>
ROORKELA <font color="black">(System Project)</font>
// THIS IS THE SUB DATATABLE HIDDEN IN DIV AND THE ID OF THE DIV IS STORED IN THE IMG ATTRIBUTE ABOVE UNDER THE 'masterProject' attribute - [masterProject="master-ROORKELA"]
<div class="hide" id="master-ROORKELA">
<table id="subProjects-table" class="table table-striped table-bordered table-hover subTable" aria-describedby="sample-table-2_info">
<thead>
<tr role="row">
<th class="sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" style="width: 255px;">Project Name</th>
<th class="sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" style="width: 186px;">Status</th>
<th class="hidden-480 sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" style="width: 203px;">Start Date</th>
<th class="hidden-480 sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" style="width: 203px;">End Date</th>
<th class="hidden-480 sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" style="width: 203px;">Targetted Date</th>
<th class="hidden-480 sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" style="width: 203px;">Project Phase</th>
<th class="hidden-480 sorting" role="columnheader" tabindex="0" aria-controls="sample-table-2" rowspan="1" colspan="1" style="width: 203px;">Defects</th>
</tr>
</thead>
<tbody role="alert" aria-live="polite" aria-relevant="all">
<tr>
<td class=" " style="width: 26%;text-align:center;vertical-align: middle;">
Sirish
</td>
<td class="hidden-480 " style="width: 10%;">
<span class="label label-sm label-warning">Minor Impact</span>
</td>
<td class=" " style="width: 10%;">Feb 12 2013</td>
<td class="hidden-480 " style="width: 10%;">Nov 12 2013</td>
<td class=" " style="width: 10%;">Jan 16 2014</td>
<td class=" " style="width: 10%;">EFT</td>
<td class=" " style="width: 15%;">
22 defects
</tr>
</tbody>
</table>
</div>
</td>
<td class="hidden-480 ">
<span class="label label-sm label-warning">Minor Impact</span>
</td>
<td class=" ">Feb 12 2013</td>
<td class="hidden-480 ">Nov 12 2013</td>
<td class=" ">Jan 16 2014</td>
<td class=" ">TESTING</td>
<td class=" ">22 defects
</tr>
</tbody>
</table>
Defining the initial table -
var oTable = $('#mastertable').dataTable( {
"aLengthMenu": [[5,10, 25, 50, 100 , -1], [5,10, 25, 50, 100, "All"]],
"iDisplayLength" : 10,
"aoColumnDefs": [
{"sWidth": "25%", "aTargets": [ 0 ] },
{"sWidth": "10%", "aTargets": [ 1 ] },
{"sWidth": "10%", "aTargets": [ 2 ] },
{"sWidth": "10%", "aTargets": [ 3 ] },
{"sWidth": "10%", "aTargets": [ 4 ] },
{"sWidth": "10%", "aTargets": [ 5 ] },
{"sWidth": "15%", "aTargets": [ 6 ] },
{"sClass": "align-left" , "aTargets": [ 0,1,4, 2,3,5,6] }
],
"sDom": '<"row"<"col-sm-4"l><"col-sm-6"f><"col-sm-1 saveas_div"T><"col-sm-1 filtering_div"C>r>t<"row"<"col-sm-6"i><"col-sm-6"p>>',
"oTableTools": {
"aButtons": [
{
"sExtends": 'csv',
"sButtonText":'Export as CSV',
"mColumns":"visible"
}
]
},
"aoColumns": [
{ "bSortable": true },
null, null, null,null, null,
{ "bSortable": true }
],
"bStateSave": true,
"fnStateSave": function (oSettings, oData) {
localStorage.setItem( 'DataTables_'+window.location.pathname, JSON.stringify(oData) );
},
"fnStateLoad": function (oSettings) {
return JSON.parse( localStorage.getItem('DataTables_'+window.location.pathname) );
}
});
Associating click events on the 'img' attributes in the table -
oTable.$('td').each( function () {
$(this).on('click','img', function () {
var nTr = $(this).parents('tr')[0];
if ( oTable.fnIsOpen(nTr) )
{
/* This row is already open - close it */
this.src = "${pageContext.request.contextPath}/theme/v_1_0/app-images/details_open.png";
oTable.fnClose( nTr );
}
else
{
/* Open this row */
this.src = "${pageContext.request.contextPath}/theme/v_1_0/app-images/details_close.png";
var masterProject = $(this).attr("masterProject");
var html = $("#"+masterProject).html();
console.log(html); // THIS IS WHERE I SEE AS UNDEFINED FOR HIDDEN TR ELEMENTS WHICH ARE HIDDEN DURING PAGINATION
oTable.fnOpen(nTr, html, 'details');
}
} );
$(this).find('img').trigger('click'); // THIS IS WHERE I"M SIMULATING CLICK EVENT TO EXPAND ALL ROWS WHILE LOADING PAGE BY DEFAULT.
});
I tried using the - fnDrawCallback method to simulate the click events, but its giving me weird results, meaning rows are expanded on alternate pages like 1,3,5 but on consecutive pages.
Sorry for this monologue, as am just trying to explain the detail of the problem.
Please pass on your valuable suggestions or solutions..
Many thanks,
Sirish.
So I added functionality on button to collapse all and expand all child rows. that will work with pagination, search and
<script>
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Full CallStack:</td>'+
'<td style="text-align:left;">'+d.call_stack+'</td>'+
'</tr>'+
'</table>';
}
$(document).ready(function() {
var isCollapse = 1;
var visited_cehck = 0;
var table = $('#example').DataTable( {
"aaData": $Json_data,
"aoColumns": [
{ "sTitle": "col1", "mData": "col1" },
{ "sTitle": "col2", "mData": "col2" },
{ "sTitle": "col3", "mData": "col3" },
{ "sTitle": "col4", "mData": "col4" },
{ "sTitle": "col5", "mData": "col5" },
{
"class": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
}
]
} );
//This function gets the length of the row and collapse and
//expend all the rows depending on the current state of the row:
function collapse_exand_rows(){
var table_length = $('#example tbody tr').length;
for (var i = 0; i < table_length; i++) {
var tr = $('.details-control').parents('tr').eq(i);
var row = table.row( tr );
if(!tr.hasClass('visited_child') || visited_cehck != 1){
if ( isCollapse === 1 ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
}
}
}
//This event handles click for on each child row to show and hide rows.
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).parents('tr');
var row = table.row( tr );
visited_cehck = 1;
tr.addClass('visited_child');
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
//This event handles navigation bar below the report to show and hide all the visible rows
$('.dataTables_paginate').bind('click', '.details-control', function(event) {
if(visited_cehck === 1){
return false;
}
collapse_exand_rows();
});
//This event handles collapse expand button click to show and hide all the visible rows
$('#collapse_expand').on('click', function(event) {
visited_cehck = 0;
if(isCollapse === 1){
$('#collapse_expand').text('Collapse All');
isCollapse = 0;
}
else{
$('#collapse_expand').text('Expand All');
isCollapse = 1;
}
collapse_exand_rows();
});
//This event handles dropdown to show and hide all the visible rows
$('select').on('change', function (event) {
collapse_exand_rows();
});
$("thead > tr", '#example').click(function(event) {
collapse_exand_rows();
})
$(':input').change(function(event) {
collapse_exand_rows();
});
});
</script>
do something like this:
var table_length = $("#mastertable tr").length;
var paginate_button = $('.paginate_button');
for(var i = 0; i< table_length; i++){
var tr = $('#mastertable tbody td.details-control').eq(i).parents('tr');
var row = table.row(tr);
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
if you have pagination :
isCollapse === 0
paginate_button.on('click',function(){
table_length = $("#example tr").length;
if ( isCollapse === 1 ) {
for(var i = 0; i< table_length; i++){
var tr = $('#example tbody td.details-control').eq(i).parents('tr');
var row = table.row(tr);
row.child.hide();
tr.removeClass('shown');
}
}
else {
// Open this row
for(var i = 0; i< table_length; i++){
var tr = $('#example tbody td.details-control').eq(i).parents('tr');
var row = table.row(tr);
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
}
});

Edit button in a view details popup in MVC 3 using jQuery

I am currently in the process of setting up an MVC entities page with the ability to list all entities of a certain type, using jQuery popups to create new entities, edit or delete existing entities.
As not all entities' details are shown in the list, I would like to provide a details view (read only) which has an edit button in case changes need to be made.
However, at the moment I have not been able to implement this and would welcome any suggestions on how to proceed. Please find the view definitions included below:
Entity Country:
/Views/Country/Index:
#model IEnumerable<MVCjQuerySample2.Entities.Country>
#{
ViewBag.Title = "Countries";
}
<h2>Countries</h2>
<span class="AddLink IconLink"><img src="/Content/Images/Create.png" alt="Add new country" /></span>
<div id="ListBlock"></div>
<div id="EditDialog" title="" class="Hidden"></div>
<div id="DeleteDialog" title="" class="Hidden"></div>
<script type="text/javascript">
$(function () {
$("#EditDialog").dialog({
autoOpen: false, width: 400, height: 330, modal: true,
buttons: {
"Save": function () {
if ($("#EditForm").validate().form()) {
$.post("/Country/Save", $("#EditForm").serialize(), function (data) {
$("#EditDialog").dialog("close");
$("#ListBlock").html(data);
});
}
},
Cancel: function () { $(this).dialog("close"); }
}
});
$("#DeleteDialog").dialog({
autoOpen: false, width: 400, height: 330, modal: true,
buttons: {
"Delete": function () {
$.post("/Country/Delete", $("#DeleteForm").serialize(), function (data) {
$("#DeleteDialog").dialog("close");
$("#ListBlock").html(data);
});
},
Cancel: function () { $(this).dialog("close"); }
}
});
$(".AddLink").click(function () {
$("#EditDialog").html("")
.dialog("option", "title", "Add new Country")
.load("/Country/Create", function () { $("#EditDialog").dialog("open"); });
});
$(".EditLink").live("click", function () {
var id = $(this).attr("itemid");
$("#EditDialog").html("")
.dialog("option", "title", "Edit Country")
.load("/Country/Edit/" + id, function () { $("#EditDialog").dialog("open"); });
});
$(".DeleteLink").live("click", function () {
var id = $(this).attr("itemid");
$("#DeleteDialog").html("")
.dialog("option", "title", "Delete Country")
.load("/Country/DeleteConfirm/" + id, function () { $("#DeleteDialog").dialog("open"); });
});
LoadList();
});
function LoadList() {
$("#ListBlock").load("/Country/List");
}
/Views/Country/List:#using MVCjQuerySample2.Helpers
#model IEnumerable<MVCjQuerySample2.Entities.Country>
<table class="CountryList">
<tr>
<th>Iso</th>
<th>Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Iso)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<span class="EditLink IconLink" itemid="#item.Id"><img src="/Content/Images/Pencil.png" alt="Edit" /></span>
<!--#Html.ImageActionLink(#"\Content\Images\Pencil.png", "Edit", "Edit", new { id = item.Id })-->
</td>
<td>
<span class="DeleteLink IconLink" itemid="#item.Id"><img src="/Content/Images/Delete.png" alt="Delete" /></span>
<!--#Html.ImageActionLink(#"\Content\Images\Delete.png", "Delete", "Delete", new { id = item.Id })-->
</td>
</tr>
}
</table>
/Views/Country/EditForm:
#model MVCjQuerySample2.Entities.Country
#using (Html.BeginForm("Save", "Country", FormMethod.Post, new { id = "EditForm" }))
{
#Html.Hidden("Id")
#Html.Hidden("CreatedBy")
#Html.Hidden("CreatedOn")
#Html.Hidden("UpdatedBy")
#Html.Hidden("UpdatedOn")
<table>
<tr>
<td>Iso</td>
<td>#Html.TextBox("Iso")</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBox("Name")</td>
</tr>
<tr>
<td>Created by</td>
<td>#Html.DisplayText("CreatedBy")</td>
</tr>
<tr>
<td>Created on</td>
<td>#Html.DisplayText("CreatedOn")</td>
</tr>
<tr>
<td>Updated by</td>
<td>#Html.DisplayText("UpdatedBy")</td>
</tr>
<tr>
<td>Updated on</td>
<td>#Html.DisplayText("UpdatedOn")</td>
</tr>
</table>
}
<script type="text/javascript">
$(function () {
$("#EditForm").validate({
rules: {
Iso: { required: true },
Name: { required: true }
}
});
});
/Views/Country/DeleteConfirm:
#model MVCjQuerySample2.Entities.Country
#using (Html.BeginForm("Delete", "Country", FormMethod.Post, new { id = "DeleteForm" }))
{
#Html.Hidden("Id")
#Html.Hidden("Iso")
#Html.Hidden("Name")
#Html.Hidden("CreatedOn")
#Html.Hidden("CreatedBy")
#Html.Hidden("UpdatedOn")
#Html.Hidden("UpdatedBy")
<table>
<tr>
<td>Iso</td>
<td>#Html.DisplayText("Iso")</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.DisplayText("Name")</td>
</tr>
<tr>
<td>Created by</td>
<td>#Html.DisplayText("CreatedBy")</td>
</tr>
<tr>
<td>Created on</td>
<td>#Html.DisplayText("CreatedOn")</td>
</tr>
<tr>
<td>Updated by</td>
<td>#Html.DisplayText("UpdatedBy")</td>
</tr>
<tr>
<td>Updated on</td>
<td>#Html.DisplayText("UpdatedOn")</td>
</tr>
</table>
}

Resources