Reusable partial view with Jquery data table with Edit button? - javascript

I have created a partial view with Jquery data table. I simply pass GridResulViewtModel to partial view where ever I need Jquery data table grid. It working fine. Now I need a column with edit button so that edit functionality could be implemented but I am unable to figure out how to implement it.
Following GridResulViewtModel I set value on each controller and use on partial view.
public class GridResulViewtModel
{
private List<ColumnsHeader> _Header;
private string _JsonHeader;
public String TableId { get; set; }
public List<string> DisplayHeader { get; set; }
public List<ColumnsHeader> Header
{
get { return _Header; }
set
{
_Header = value;
StringBuilder headerProperty = new StringBuilder();
headerProperty.Append("[");
foreach (var item in Header)
{
if (!string.IsNullOrEmpty(item.DefaultContent))
headerProperty.Append("{ 'mDataProp': '" + item.DataField + "', sDefaultContent: '" + item.DefaultContent + "' },");
else
headerProperty.Append("{ 'mData': '" + item.DataField + "', sDefaultContent: '" + item.DefaultContent + "' },");
}
headerProperty.Append("]");
_JsonHeader = headerProperty.ToString().Replace(",]", "]");
}
}
public String JsonData { get; set; }
public String JsonHeader { get { return _JsonHeader; } }
public string URL { get; set; }
}
Setting value from controller like this
public ActionResult Index()
{
try
{
GridResulViewtModel model = new GridResulViewtModel();
List<ColumnsHeader> lstColumnsHeader = new List<ColumnsHeader>();
var data = customerService.GetCustomers();
// var Edit = new ColumnsHeader() { DataField = null, DefaultContent = "<button style=\"color:green;\">I am text</button>" };
var Edit = new ColumnsHeader() { DataField = "", DefaultContent = "How to make it Edit button?" };
var CustomerID = new ColumnsHeader() { DataField = "CustomerID", DefaultContent = "" };
var firstName = new ColumnsHeader(){ DataField="FirstName", DefaultContent =""};
var LastName = new ColumnsHeader() { DataField = "LastName", DefaultContent = "" };
var CustomerCode = new ColumnsHeader() { DataField = "CustomerCode", DefaultContent = "" };
lstColumnsHeader.Add(CustomerID);
lstColumnsHeader.Add(firstName);
lstColumnsHeader.Add(LastName);
lstColumnsHeader.Add(CustomerCode);
lstColumnsHeader.Add(Edit);
model.Header = lstColumnsHeader;
//model.Header = new List<string> { "CustomerID", "FirstName", "LastName", "CustomerCode" };
model.DisplayHeader = new List<string> { "Edit", "ID", "First Name", "Last Name", "Customer Code" };
model.TableId = "tblCustomer";
model.JsonData = JsonConvert.SerializeObject(data);
model.URL = "/Customer/GetCustomer";
return ViewResult("Index", model);
}
catch (Exception ex)
{
throw;
}
and this is partial view I result on mulitple views
<script type="text/javascript">
$(document).ready(function () {
try {
var table = $(#Model.TableId);
var tableData = #Html.Raw(Model.JsonData)
var tableHeader = #Html.Raw(Model.JsonHeader)
oTable = $(table).dataTable(
{
"processing": true,
"serverSide": true,
"ajax":
{
"url": "#Model.URL",
"type": "POST",
"dataType": "JSON"
},
"aaData": tableData,
"aoColumns": tableHeader,
"bPaginate": true,
//"bLengthChange": true,
//"bFilter": true,
//"bSort": true,
//"bInfo": true,
//"bAutoWidth": false,
//"bStateSave": false,
//"idisplayLength": 15,
"sPaginationType": "full_numbers",
"bDeferRender": true,
// "sDom": 'T<"clear">lfrtip',
//"oTableTools":
// {
// "sSwfPath": "../Content/DataTables-1.9.4/extras/TableTools/media/swf/copy_csv_xls_pdf.swf",
// "aButtons": [ "copy",
// {
// "sExtends": "collection",
// "sButtonText": "Save",
// "aButtons": [ "csv", "pdf" ]
// }
// ]
// }
});
}
catch (err) {
//alert("Error in operation! " + err);
}
});
</script>
</div>
}
I am still unable to understand how should I set Id as data-id attribute on Edit button?

The code below updates the DataTable options to version 1.10+ and adds an event handler that lets you get hold of a data object for a row.
oTable = $(table).dataTable(
{
"processing": true,
"serverSide": true,
"ajax":
{
"url": "#Model.URL",
"type": "POST",
"dataType": "JSON"
},
"data": tableData,
"columns": tableHeader,
"paging": true,
//"bLengthChange": true,
//"bFilter": true,
//"bSort": true,
//"bInfo": true,
//"bAutoWidth": false,
//"bStateSave": false,
//"idisplayLength": 15,
"pagingType": "full_numbers",
"deferRender": true,
// "sDom": 'T<"clear">lfrtip',
//"oTableTools":
// {
// "sSwfPath": "../Content/DataTables-1.9.4/extras/TableTools/media/swf/copy_csv_xls_pdf.swf",
// "aButtons": [ "copy",
// {
// "sExtends": "collection",
// "sButtonText": "Save",
// "aButtons": [ "csv", "pdf" ]
// }
// ]
// }
});
// row button on click handler
$("#example tbody").on("click", "button", function () {
var tr = $(this).closest("tr");
var data = oTable.rows(tr).data()[0];
// do what you need to do with the row data
});

Related

Initialise same datatable with two functions

I have two functions (load_data and fetch_data) inside of my datatables script. They are both using different ajax calls.
My table (name: product_data) and the script is working as expected but this error message is shown with the first page load:
"DataTables warning: table id=product_data - Cannot reinitialise
DataTable"
I think this error comes because I have a mistake in mergin these two functions together in one script. Could you help me how the two functions can initialise my table "product_data" correctly ?
$(document).ready(function() {
// Start Function 1
load_data();
function load_data(is_category) {
var dataTable = $('#product_data').DataTable({
"processing": true,
"serverSide": true,
"sDom": "rtipl",
"order": [],
"ajax": {
url: "fetch.php",
type: "POST",
data: {
is_category: is_category
}
},
"columnDefs": [{
"targets": [2],
"orderable": false,
}, ],
});
}
// Script for Function 1 //
$(document).on('change', '#category', function() {
var category = $(this).val();
$('#product_data').DataTable().destroy();
if (category != '') {
load_data(category);
} else {
load_data();
}
});
// Start Function 2
fetch_data('no');
function fetch_data(is_date_search, start_date = '', end_date = '') {
var dataTable = $('#product_data').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
url: "fetch.php",
type: "POST",
data: {
is_date_search: is_date_search,
start_date: start_date,
end_date: end_date
}
}
});
}
// Script for Function 2 //
$('#search').click(function() {
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if (start_date != '' && end_date != '') {
$('#product_data').DataTable().destroy();
fetch_data('yes', start_date, end_date);
} else {
alert("Both Date is Required");
}
});
// Search Field
var datatable = $('#product_data').DataTable();
$('#searchfield').on('keyup', function() {
datatable.search(this.value).draw();
});
});
part of fetch.php
...
if($_POST["is_date_search"] == "yes")
{
$query .= 'order_id BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
if(isset($_POST["is_category"]))
{
$query .= "order_item = '".$_POST["is_category"]."' AND ";
}
...
At the backebd i,e fetch.php you may have validations
like check if start_date,end_date exist or not
check if is_category exist or not and fetch only for valid post data
$(document).ready(function() {
// Start Function 1
function load_data() {
//first recive all inputs here
let is_category = $("#category").val();
let start_date = $('#start_date').val();
let end_date = $('#end_date').val();
//at the backebd i,e fetch.php you may have validations
//i.e start_date,end_date exist or not
//is_category exist or not
//and initialise datatables once only
var dataTable = $('#product_data').DataTable({
"processing": true,
"serverSide": true,
"sDom": "rtipl",
"order": [],
"ajax": {
url: "fetch.php",
type: "POST",
data: {
is_category: is_category,
start_date: start_date,
end_date: end_date
}
},
"columnDefs": [{
"targets": [2],
"orderable": false,
}, ],
});
}
//calling the function on document load
load_data();
$(document).on('change', '#category', function() {
$('#product_data').DataTable().destroy();
load_data();
});
$('#search').click(function() {
if (start_date != '' && end_date != '') {
$('#product_data').DataTable().destroy();
load_data();
} else {
alert("Both Date is Required");
}
});
// Search Field
var datatable = $('#product_data').DataTable();
$('#searchfield').on('keyup', function() {
datatable.search(this.value).draw();
});
})

number of index data each row in datatable

I want to create and show number sort ascending data in datatables like in this picture
index number
and I don't have sorted data number in database and my json data
this is my code:
$(document).ready(function() {
$('#dataya').DataTable({
lengthChange: false,
ajax: {
url: "http://localhost/jdih_webservice/api/xxxx",
dataSrc: ""
},
columns: [
{ data: "id_dokumen"},
{ data: "judul"},
{ data: "subjek"}
],
select: true
});
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
var myTable = $('#dataya').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"bDestroy": true,
"autoWidth": true,
"data": [],
"columns": [{
"title": "ID",
"data": "id_dokumen"
}, {
"title": "Judul",
"data": "judul"
}, {
"title": "Subjek",
"data": "subjek"
}],
"order": [[ 1, 'asc' ]]
});
if(start_date != '' && end_date !='')
{
var startDate = new Date(start_date);
var tglmulai = startDate.getFullYear();
var endDate = new Date(end_date);
var tglselesai = endDate.getFullYear();
let url = 'http://localhost/jdih_webservice/api/xxxx';
fetch(url)
.then(res => res.json())
.then((out) => {
var resultProductData = out.filter(function(a) {
var createdAt = new Date(a.tgltetap);
var tgldata = createdAt.getFullYear();
if( tgldata >= tglmulai && tgldata <= tglselesai ) return a;
});
myTable.clear();
$.each(resultProductData, function (index, value) {
myTable.row.add(value);
});
myTable.draw();
})
.catch(err => { throw err });
}
});
});
Anyone could help? , so appreciate thanks
and maybe if you not busy could you create/build in jsfiddle
This code is from this DataTables thread and should do what you want. It's using an additional column for the indexes:
dataTable.on( 'order.dt search.dt', function () {
dataTable.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();

Add a Count for each button using Data Tables

I am using data tables. Currently, it is working as expected, hower I would like to have the Add and Remove Buttons have some sort of count. For example AddButton_0
How would I do this using Data Tables?
var url = "/ClientSetup/GetCatalogueContracts";
var contractsTable = $('#catalogueContractsTable').DataTable({
sAjaxSource: url,
columns: [
{ "data": "ID" },
{ "data": "Selected"},
{ "data": "Name"},
{ "data": "ContractType"},
{ "data": "StartDate"},
{ "data": "TerminationDate"},
{ "button": "Action" }
],
serverSide: true,
sDom: 't<"dt-panelfooter clearfix"ip>',
pageLength: pageSize,
bSort: false,
bLengthChange: false,
bSearch: true,
paging: true,
searching: true,
order: [[2, "asc"]],
language: {
emptyTable: "No contracts found.",
zeroRecords: "No contracts found.",
info: "_START_ to _END_ of _TOTAL_",
paginate: {
first: "First",
previous: "Previous",
next: "Next",
last: "Last"
}
},
columnDefs: [
{
targets: [0],
visible: false
},
{
targets: [1],
visible: false
},
{
targets: [2]
},
{
targets: [3],
sClass: "hidden-xs hidden-sm contractType"
},
{
targets: [4],
sClass: "hidden-xs fromDate"
},
{
targets: [5],
sClass: "hidden-xs terminationDate"
},
{
data: null,
targets: [6],
sClass: "updateTableRow text-center",
render: function ( data, type, full, meta )
{
var id = data["ID"];
return `<button class=\"btn btn-success br2 btn-xs fs12 table-btn button-selector-${id}\" id=\"AddContractBtn\">Add</button>`;
}
}
],
drawCallback: function( settings ) {
disableInvalidContracts();
},
autoWidth: false
});
// make sure already selected rows cannot be added again.
var excludeIds = getExcludeIds();
$.each(excludeIds, function() {
var button = $("#AddContractBtn.button-selector-" + this);
button.addClass("disabled");
button.prop('disabled', true);
});
}
#* Adding and Removing Data from both Tables *#
contractsTable.on('click', '#AddContractBtn', function () {
var $row = $(this).closest("tr");
#*Track Contract IDs that have been removed from the unselected table*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids.push($row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
var addRow = contractsTable.row($row);
var data = addRow.data();
data.Selected = true;
selectedContractsTable.row.add(addRow.data()).draw( false );
setSelectedInputForContract('true', data.ID);
disableInvalidContracts();
});
selectedContractsTable.on('click', '#RemoveContractBtn', function () {
var $row = $(this).closest('tr');
var addRow = selectedContractsTable.row($row);
var data = addRow.data();
data.Selected = false;
addRow.data(data);
addRow.remove().draw();
#* Remove the Contract ID from the exclide ids hidden input*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids = ids.filter(i => i !== $row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
setSelectedInputForContract('false', data.ID);
disableInvalidContracts();
});
I am looking for a way that I can add a Count for each of the buttons for example `AddButton_0 I am unsure if there is an option to use a count on DataTables. Or whether I could use JQuery?
Try this : you can have global variable and increment it for each access of button creation function. Click handler for add and remove button can be created with start with attribute selector in jquery.
See below code
var count = 0;
var url = "/ClientSetup/GetCatalogueContracts";
var contractsTable = $('#catalogueContractsTable').DataTable({
sAjaxSource: url,
columns: [
{ "data": "ID" },
{ "data": "Selected"},
{ "data": "Name"},
{ "data": "ContractType"},
{ "data": "StartDate"},
{ "data": "TerminationDate"},
{ "button": "Action" }
],
serverSide: true,
sDom: 't<"dt-panelfooter clearfix"ip>',
pageLength: pageSize,
bSort: false,
bLengthChange: false,
bSearch: true,
paging: true,
searching: true,
order: [[2, "asc"]],
language: {
emptyTable: "No contracts found.",
zeroRecords: "No contracts found.",
info: "_START_ to _END_ of _TOTAL_",
paginate: {
first: "First",
previous: "Previous",
next: "Next",
last: "Last"
}
},
columnDefs: [
{
targets: [0],
visible: false
},
{
targets: [1],
visible: false
},
{
targets: [2]
},
{
targets: [3],
sClass: "hidden-xs hidden-sm contractType"
},
{
targets: [4],
sClass: "hidden-xs fromDate"
},
{
targets: [5],
sClass: "hidden-xs terminationDate"
},
{
data: null,
targets: [6],
sClass: "updateTableRow text-center",
render: function ( data, type, full, meta )
{
var button = `<button class=\"btn btn-success br2 btn-xs fs12 table-btn button-selector-${id}\" id=\"AddContractBtn' + count + '\">Add</button>`;
count++; // increment count
var id = data["ID"];
return button;
}
}
],
drawCallback: function( settings ) {
disableInvalidContracts();
},
autoWidth: false
});
// make sure already selected rows cannot be added again.
var excludeIds = getExcludeIds();
$.each(excludeIds, function() {
var button = $("#AddContractBtn.button-selector-" + this);
button.addClass("disabled");
button.prop('disabled', true);
});
}
#* Adding and Removing Data from both Tables *#
contractsTable.on('click', 'button[id^=AddContractBtn]', function () {
var $row = $(this).closest("tr");
#*Track Contract IDs that have been removed from the unselected table*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids.push($row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
var addRow = contractsTable.row($row);
var data = addRow.data();
data.Selected = true;
selectedContractsTable.row.add(addRow.data()).draw( false );
setSelectedInputForContract('true', data.ID);
disableInvalidContracts();
});
selectedContractsTable.on('click', 'button[id^=RemoveContractBtn]', function () {
var $row = $(this).closest('tr');
var addRow = selectedContractsTable.row($row);
var data = addRow.data();
data.Selected = false;
addRow.data(data);
addRow.remove().draw();
#* Remove the Contract ID from the exclide ids hidden input*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids = ids.filter(i => i !== $row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
setSelectedInputForContract('false', data.ID);
disableInvalidContracts();
});

How to delete multiple rows in Jqgrid MVC

My view is displayed by external javascript instead of in the view itself. How do i delete multiple rows in jqgrid? I have the multiselect and multiboxonlyset equals to true. Here are my codes
View (the view is formatted in "~/Scripts/TodoList.js")
#{
ViewBag.Title = "Index";
}
<h2>TodoList</h2>
<div>
<table id="grid"></table>
<div id="pager"
</div>
<link type="text/css" rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
Get Selected id's
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
#*<script src="~/Scripts/jquery-1.12.4.min.js" type ="text/javascript"></script>*#
<script src="~/Scripts/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="~/Scripts/TodoList.js" type="text/javascript"></script>
Todolist.js (Jqgrid)
/* File Created: February 17, 2017 */
$(function () {
$("#grid").jqGrid({
url: "/TodoList/GetTodoLists",
datatype: 'json',
mtype: 'Get',
colNames: ['Id', 'Task Name', 'Task Description', 'Target Date', 'Severity', 'Task Status'],
colModel: [
{ key: true, hidden: true, name: 'Id', index: 'Id', editable: true },
{ key: false, name: 'TaskName', index: 'TaskName', editable: true },
{ key: false, name: 'TaskDescription', index: 'TaskDescription', editable: true },
{
key: false, name: 'TargetDate', id: "elem", index: 'TargetDate', editable: true, formatter: 'date', formatoptions: { newformat: 'd/m/Y' },
editoptions: { dataInit: function (elem) { $(elem).datepicker(); } }
},
{ key: false, name: 'Severity', index: 'Severity', editable: true, edittype: 'select', editoptions: { value: { 'L': 'Low', 'M': 'Medium', 'H': 'High'}} },
{ key: false, name: 'TaskStatus', index: 'TaskStatus', editable: true, edittype: 'select', editoptions: { value: { 'A': 'Active', 'I': 'InActive'}}}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 20, 30, 40],
height: '100%',
viewrecords: true,
// Bug Codes
// loadonce:true, //compulsory for search
//cellEdit: true, //inline edits
//cellsubmit: 'clientArray', //inline edit
caption: 'Todo List',
sortname: 'id',
sortorder: 'desc',
multiselect: true,
multiboxonly: true,
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
autowidth: true,
}).navGrid('#pager', { edit: true, add: true, del: true, search: true, refresh: true }, //search: true
{
// edit options
zIndex: 100,
url: '/TodoList/Edit',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
// add options
zIndex: 100,
url: "/TodoList/Create",
closeOnEscape: true,
closeAfterAdd: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
//delete options
zIndex: 100,
url: "/TodoList/Delete" + ,
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
msg: "Are you sure you want to delete this task?",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
});
});
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using TodoListApplication.DBContext;
using TodoListApplication.Models;
namespace TodoListApplication.Controllers
{
public class TodoListController : Controller
{
//
// GET: /TodoList/
public ActionResult Index()
{
return View();
}
TodoContext db = new TodoContext();
public JsonResult GetTodoLists(string sidx, string sord, int page, int rows) //Gets the todo Lists.
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var todoListsResults = db.TodoLists.Select(
a => new
{
a.Id,
a.Severity,
a.TargetDate,
a.TaskDescription,
a.TaskName,
a.TaskStatus
});
int totalRecords = todoListsResults.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{
todoListsResults = todoListsResults.OrderByDescending(s => s.TaskName);
todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
todoListsResults = todoListsResults.OrderBy(s => s.TaskName);
todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = todoListsResults
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
// TODO:insert a new row to the grid logic here
[HttpPost]
public string Create([Bind(Exclude = "Id")] TodoList objTodo)
{
string msg;
try
{
if (ModelState.IsValid)
{
db.TodoLists.Add(objTodo);
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successful";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
public string Edit(TodoList objTodo)
{
string msg;
try
{
if (ModelState.IsValid)
{
db.Entry(objTodo).State = EntityState.Modified;
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfull";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
public string Delete(int Id)
{
TodoList todolist = db.TodoLists.Find(Id);
db.TodoLists.Remove(todolist);
db.SaveChanges();
return "Deleted successfully";
}
}
}
jqGrid send comma-separated list of ids in case of deleting rows in multiselect: true mode. Thus you should change string Delete(int Id) to void Delete(string id). The corresponding code could be about the following:
public void Delete(string id)
{
var ids = id.Split(',');
foreach (var id in ids) {
TodoList todolist = db.TodoLists.Find(int.Parse(id));
db.TodoLists.Remove(todolist);
}
db.SaveChanges();
}
I'd recommend you to consider too use loadonce: true option and to simplify your co return all items at once. It's the best scenario in case of displaying small number of rows (less as 1000 for example). It will simplify your server code and to improve the performance (responsibility) of the grid.
I'd recommend you additionally to verify that you use the latest version of free jqGrid (which you can download from NuGet or to load directly from CDN). You should review jqGrid options, which you use and to remove unneeded or wrong options/parameters.
I have solved my problem, with the help by #Oleg codes.
1st:
I found out that the id name that my controller uses to pass the id is "id", while my delete method in my controller says "Id" :
public string Delete(int Id) // < see this
{
TodoList todolist = db.TodoLists.Find(Id);
db.TodoLists.Remove(todolist);
db.SaveChanges();
return "Deleted successfully";
}
click here to see the debug result, pay attention to Form Data Section
So there is a name mismatched between the id specified by controller and the id that i specified in my delete method
2nd:
So i modified my delete method in controller to become:
public ActionResult Delete(string id)
{
var ids = id.Split(',');
foreach (var idsss in ids)
{
TodoList todolist = db.TodoLists.Find(int.Parse(idsss));
db.TodoLists.Remove(todolist);
}
db.SaveChanges();
var result = new { msg = "Deletion Successful ! " };
return Json(result, JsonRequestBehavior.AllowGet);
}
Now it works now, thanks to #Oleg !

how to get the Selected item in dropdownlist while click the Edit button in inline kendo grid in asp

How to Display the Selected Item from Database in Kendo Grid while click the Edit Button
**My Coding Like**
var grid= $("#DivUser").kendoGrid(
{
dataSource: DataSource4,
scrollable: true,
sortable: true,
filterable: false,
reorderable: true,
resizable: true,
pageable: true,
toolbar: [ { text : "Add new record", name: "popup",
iconClass: "k-icon k-add"} ],
editable : {
mode : "inline"
columns: [
{
field: "LoginName",
title: "Login Name",
width:"175px"
},
{
field: "ScopeId",
title: "Scope Id",
editor: ScopeDropDownEditor
},
{
command: ["edit", "destroy"],
title: " ",
width: "175px"
}
]
}).data("kendoGrid");
var DataSourceScope = new kendo.data.DataSource(
{
transport:
{
read:
{
url: "WebServices/Project.asmx/GetScope",
data: "{}",
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json'
},
parameterMap: function(options, operation)
{
if (operation == 'read')
return kendo.stringify(options);
}
},
schema:
{
data: function(Data)
{
return (Data.d);
},
model:
{
id: "ScopeId",
fields:
{
ScopeId: { type: "number"},
ScopeName: { type: "string"}
}
}
},
error: function(e)
{<br>
var xhr = e[0];
var statusCode = e[1];
var errorThrown = e[2];
alert('DataSourceScope - ' + xhr + ', ' + statusCode + ', ' + errorThrown);
}<br>
});
function ScopeDropDownEditor(container, options)
{
$('
data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList(
{
autoBind: false,
dataSource: DataSourceScope
});
} `
in my webservice code like
public class Scopes
{
int _ScopeId;
string _ScopeName;
public int ScopeId
{
get { return _ScopeId; }
set { _ScopeId = value; }
}
public string ScopeName
{
get { return _ScopeName; }
set { _ScopeName = value; }
}
public Scopes() { }
public Scopes(int ScopeId, string ScopeName) { this.ScopeId = ScopeId; this.ScopeName = ScopeName; }
}
[WebMethod]
public List<Scopes> GetScope()
{
string StrConnectionString = ConfigurationManager.ConnectionStrings["sample"].ConnectionString;
SqlConnection SqlConnection1 = new SqlConnection(StrConnectionString);
SqlCommand SqlCommand1 = new SqlCommand("select distinct ScopeId,(select ScopeName from Scope2 where Scope2.ScopeID=User2.ScopeId)as ScopeName from User2", SqlConnection1);
DataTable DataTable1 = new DataTable();
SqlDataAdapter SqlDataAdapter1 = new SqlDataAdapter(SqlCommand1);
SqlDataAdapter1.Fill(DataTable1);
List<Scopes> ListScope = new List<Scopes>();
foreach (DataRow DataRow1 in DataTable1.Rows)
{
ListScope.Add(new Scopes(Convert.ToInt32(DataRow1["ScopeId"]), Convert.ToString(DataRow1["ScopeName"])));
}
return ListScope;
}
this is Ok..
But after Click Edit button the dropdownlist items like 1st item
for Example
ScopeName id dropdownlist
items Admin, Developer,tester
in database james is tester
if i click Edit Button Means
Name ScopeName
James admin
developer
tester
How to Bind and How i displya the SElected items?
thankx in advance.
edited
fetch data directly using java script
var xhReq = new XMLHttpRequest();
xhReq.open("POST", 'WebServices/Project.asmx/GetScope', false);
xhReq.send(null);
var DataSourceScope = JSON.parse(xhReq.responseText);
function ScopeDropDownEditor(container, options)
{
$('<input name="' + options.field + '"/>').appendTo(container).kendoDropDownList({
dataTextField: "ScopeName",
dataValueField: "ScopeId",
dataSource: DataSourceScope.d
});
}

Categories