I am new to C# and ASP.NET MVC and specially views.
I have the following problem
I have this code
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult ManageEmployee(int cntID, string command)
{
//repository = new ContactRepository();
cntadrRepository = new ContactAddressCountryRepository();
//addressRepository = new AddressRepository();
if (!String.IsNullOrEmpty(command) && command.Equals("edit"))
{
var cdrcnts = cntadrRepository.GetById(cntID);
ViewBag.IsUpdate = true;
//return View("_ManageEmployee", cdrcnts);
return View("Index", cdrcnts);
//return View("Index");
}
else
{
ViewBag.IsUpdate = false;
//return View("_ManageEmployee");
return View("Index");
}
}
that returns my form empty when I click on Add button
when I click on Add I get the form slide in and the grid slide out and I can enter a new record and then after clicking on save I return to my grid with the new record.
Now the problem is When I click on Edit I have the view with only an Add button that when I click on I get the result that I want to get, directly, when I click on Edit which is the form filled with the required information
I think that I have a problem when I return the view.
What I want is that I return that form populated with the contact information when I click on Edit and stay in the same page that shows again the grid and the edited record and not have that empty page with the Add button that I need to click on again to have the required result.
Thank you for your help.
<script type="text/javascript">
$.ig.loader({
scriptPath: './js/',
cssPath: './css/',
resources: 'igGrid.*',
ready: function () {
$.getJSON("Home/GetAll", null, function (data) {
var headerTextValues = ["Relation to Will maker", "First Name", "Last Name","","",""];
$('#employeeGrid').igGrid({
expandCollapseAnimations: true,
animationDuration: 1000,
expandTooltip: "Expand to View Details",
collapseTooltip: "Hide details",
height: "400px",
width: "800px",
dataSource: data,
responseDataKey: "Records",
//dataSourceType: "json",
autoGenerateLayouts: false,
autoGenerateColumns: false,
rowEditDialogContainment: "owner",
showReadonlyEditors: false,
columns: [
{ headerText: headerTextValues[0], key: "cntID", width: 200 },
{ headerText: headerTextValues[1], key: "cntFirstName", width: 175 },
{ headerText: headerTextValues[2], key: "cntLastName", width: 175 },
//{ headerText: headerTextValues[3], key: "Age", width: 175 },
{ headerText: headerTextValues[4], key: "UpdateRow", width: 110, template: "<a href='Home/ManageEmployee?cntID=${cntID}&command=edit' class='editDialog'>Edit</a>" },
{ headerText: headerTextValues[5], key: "DeleteRow", width: 50, template: "<a href='Home/Delete?cntID=${cntID}' class='confirmDialog'><button>Delete</button></a>" },
],
initialDataBindDepth: -1,
primaryKey: 'cntID',
width: '800',
updateURL: "Home/Update",
/*columnLayouts: [
{
key: "cntD",
responseDataKey: "Records",
autoGenerateColumns: false,
autoGenerateLayouts: false,
generateCompactJSONResponse: false,
primaryKey: "cntID",
foreignKey: "cntAddressID",
columns: [
{ key: "cntId", headerText: "Address Id", width: "150px" },
{ key: "cntAddressID", headerText: "Address", width: "150px" },
//{ key: "Street", headerText: "Street", width: "150px" },
//{ key: "City", headerText: "City", width: "150px" },
//{ key: "Zip", headerText: "Zip", width: "150px" }
]
}
],*/
features: [
{
name: "Selection",
mode: "row",
multipleSelection: false
},
{
name: 'Hiding'
},
{
name: 'Paging',
type: 'local',
pageSize: 10,
inherit: true
},
{
name: 'Filtering'
},
{
name: "ColumnMoving",
mode: "immediate",
//columnDragStart: function (event, ui) {
// ui.owner.element.find('tr td:nth-child(' + (ui.columnIndex + 1) + ')').addClass("ui-state-moving");
// colMovingKey = ui.columnKey;
//},
//columnDragEnd: function (event, ui) {
// var grid = $(event.target).data('igGrid');
// var newindex = grid.options.columns.indexOf(grid.columnByKey(colMovingKey)) + 1;
// grid.element.find('tr td:nth-child(' + newindex + ')').removeClass("ui-state-moving");
//},
addMovingDropdown: true,
mode: "deferred",
type: "render"
}
],
});
});
}
});
$(document).ready(function () {
$.ajaxSetup({ cache: false });
$(".editDialog").live("click", function (e) {
e.preventDefault();
var url = $(this).attr('href');
$("#dialog-edit").load(url);
$("#dialog-edit").toggle("slide");
});
$("#openDialog").live("click", function (e) {
e.preventDefault();
var url = $(this).attr('href');
$("#dialog-create").load(url);
$("#dialog-create").toggle("slide");
})
});
</script>
#section featured {
<section class="featured">
<div class="overlap">
<div class="content-wrapper">
<!-- the igHierarchicalGrid target element-->
<table id="employeeGrid" style="width: auto;"></table>
<p>
<a id='openDialog' href='Home/ManageEmployee?cntID=0&command=create' class='openDialog ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only' style="color: white;">Add Employee</a>
</p>
<div id="btn">
<button id="add">Add</button>
</div>
Related
I am having issues with Free Jqgrid where I can not get it to post to my developer version of Microsoft SQL server. I am using Microsoft visual studios. I am using entity framework 6 for the database connections. When I use break points it doesn't seem to hit my createbid, editbid, or delete bid. I also don't get any errors in console.
I have looked through and done many of the tutorials for editing updating and adding lines. I had the same problem. I cant find an answer that works on stack overflow through my research.
I published it to IIS to see if maybe it was something with visual studios and to see if anything changes but i did get some errors this time. It is not finding the /Home/GetBidValues, Home/EditBid, /Home/CreateBid, /Home/DeleteBid. this is weird because with visual studios it was at least getting data into the grid and showing it. So I will look into this further and see if there is something wrong with my ajax and also with my C# code.
Here is my Jquery file
$(function () {
$("#grid").jqGrid
({
url: "/Home/GetBidValues",
datatype: 'json',
mtype: 'Get',
colNames: ['Client Cost', 'ElementId', 'Note', 'Area', 'Element', 'Item', 'Qty', 'Description'], //Othr Misc
//colModel takes the data from controller and binds to grid
colModel: [
{
key: true,
hidden: true,
name: 'ElementId',
index: 'ElementId',
frozen: true,
editable: false
}, {
key: false,
name: 'Note',
index: 'Note',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'Area',
index: 'Area',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'Element',
index: 'Element',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
name: 'Item',
index: 'Item',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'QTY',
index: 'QTY',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'Description',
index: 'Description',
frozen: true,
editable: true,
width: 70,
align: 'center'
}],
pager: '#pager',
gridview: true,
ignoreCase: true,
rowNumbers: false,
shrinkToFit: false,
height: '100%',
width: 1000,
viewrecords: true,
footerrow: true,
emptyrecords: 'No records to display',
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
}
});
$('#grid').jqGrid( 'inlineNav','#pager', {
edit: true,
add: true,
del: true,
cancel: true,
search: true,
refresh: true,
editparams: {
keys:true
}
}, {
// edit options
zIndex: 100,
url: '/Home/EditBid',
//datatype: 'json',
//mtype: 'Post',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},{//add
zIndex: 100,
url: "/Home/CreateBid",
closeOnEscape: true,
closeAfterAdd: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
}, {
// delete options
zIndex: 100,
url: "/Home/DeleteBid",
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
reloadaftersubmit: true,
msg: "Are you sure you want to delete this task?",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
});
});
Here is my C# file
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ERPWebAppTest.Models;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
namespace ERPWebAppTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
Test1Entities db = new Test1Entities();
[HttpGet]
public JsonResult GetBidValues(string sidx, string sord, int page, int rows)
{
//old code
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var Results = db.BidDetails.Select(
a => new
{
a.ElementID,
a.Note ,
a.Area ,
a.Element ,
a.Item ,
a.QTY ,
a.Descr ,
});
int totalRecords = Results.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{
Results = Results.OrderByDescending(s => s.ElementID);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
Results = Results.OrderBy(s => s.ElementID);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = Results
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public string CreateBid([Bind(Exclude = "ElementID")] BidDetail obj)
{
Test1Entities db = new Test1Entities();
string msg;
try
{
if (ModelState.IsValid)
{
db.BidDetails.Add(obj);
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfully";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
[HttpPost]
public string EditBid(BidDetail obj)
{
Test1Entities db = new Test1Entities();
string msg;
try
{
if (ModelState.IsValid)
{
db.Entry(obj).State = EntityState.Modified;
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfull";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
[HttpPost]
public string DeleteBid(int ElementID)
{
Test1Entities db = new Test1Entities();
BidDetail list = db.BidDetails.Find(ElementID);
db.BidDetails.Remove(list);
db.SaveChanges();
return "Deleted successfully";
}
}
}
I see many small small issues into your jqgrid code, which can be one of the reason of your current problem. You can change them in order to make the above code workable.
colModel items numbers are not exactly same as colNames items. You wrote Client Cost at first in colNames but in colModel you haven't used that.
You also haven't pasted your html code which is required to point jqgrid to load on table element.
for example:
<table id="grid" class="table table-bordered"></table>
<div id="pager"></div>
I am also assuming that you have already added free-jqgrid scripts and jquery-ui css files.
Also, in your c# code you can remove redundancy by using a global db initialization.
I have created a demo jqgrid which you can alter according your requirement:
<div class="row">
<table id="grid" class="table table-bordered"></table>
<div id="pager"></div>
</div>
#section Scripts{
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/free-jqGrid/jquery.jqgrid.min.js"></script>
<script type="text/javascript">
$(function () {
$("#grid").jqGrid
({
url: "/Home/GetBidValues",
datatype: 'json',
mtype: 'Get',
colNames: ['LanguageId', 'LanguageName', 'LanguageDescription', 'CreatedBy', 'CreatedOn'], //Othr Misc
//colModel takes the data from controller and binds to grid
colModel: [
//{ name: "act", template: "actions", align: "left", width: 58 },
{
key: true,
hidden: true,
name: 'LanguageId',
index: 'LanguageId',
editable: false
}, {
key: false,
name: 'LanguageName',
index: 'LanguageName',
frozen: true,
editable: true,
align: 'center'
}, {
key: false,
name: 'LanguageDescription',
index: 'LanguageDescription',
editable: true,
align: 'center'
}, {
key: false,
name: 'CreatedBy',
index: 'CreatedBy',
editable: true,
align: 'center'
}, {
name: 'CreatedOn',
index: 'CreatedOn',
editable: true,
align: 'center'
}],
//cmTemplate: { editable: true, autoResizable: true },
iconSet: "fontAwesome",
rowNum: 10,
//autoResizing: { compact: true },
rowList: [5, 10, 20, "10000:All"],
viewrecords: true,
pager: jQuery('#pager'),
toppager: false,
inlineEditing: { keys: true, position: "afterSelected" },
rownumbers: true,
sortname: "invdate",
sortorder: "desc",
caption: "Demonstration of the usage custom action buttons",
autowidth: true,
shrinkToFit: false,
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "LanguageId"
}
});
jQuery("#grid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter:
false, defaultSearch: "cn", multipleSearch: true, searchOperators: true, search: true
}); //searchOnEnter: false means records are filtered as soon as the text is
entered by the user
jQuery("#grid").jqGrid('navGrid', '#pager', { add: true, edit: true, del: true, search: true, refresh: true,view:true }, {
// edit options
zIndex: 100,
url: '/Home/EditBid',
//datatype: 'json',
//mtype: 'Post',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
}, {//add
zIndex: 100,
url: "/Home/CreateBid",
closeOnEscape: true,
closeAfterAdd: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
}, {
// delete options
zIndex: 100,
url: "/Home/DeleteBid",
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
reloadaftersubmit: true,
msg: "Are you sure you want to delete this task?",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
});
});
</script>
}
I have Kendo Grid in my view. I have specified read , edit and delete each as of type HTTPPOST. But when I try to edit or delete i get an error that : "A public action method 'UpdateDetails' was not found on controller 'Nop.Plugin.Misc.CategoryWiseShipping.Controllers.ShippingChargeController'." for update Action and similarly one other for delete option.
Interesting thing is that it works fine on my local machine but throws error when published to server
I have searched extensivelly on google but couldn't find the reason as to why it is happening.
This is the controller actionMethod
[HttpPost]
public ActionResult UpdateDetails(ShippingChargeModel shippingChargeModel)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts))
return AccessDeniedView();
if (shippingChargeModel.SchoolEmail == null)
{
ErrorNotification(" Email can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleStartDate == null)
{
ErrorNotification(" Sale start date can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleEndDate == null)
{
ErrorNotification(" Sale end date can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleEndDate < shippingChargeModel.SaleStartDate)
{
ErrorNotification(" Sale start date should be less than sale end date!!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
var modelFromDb = _catShippingService.GetRecord(shippingChargeModel.Id);
modelFromDb.SaleEndDate = shippingChargeModel.SaleEndDate.Value.AddMinutes(330);
modelFromDb.SaleStartDate = shippingChargeModel.SaleStartDate.Value.AddMinutes(330);
modelFromDb.SchoolEmail = shippingChargeModel.SchoolEmail;
modelFromDb.ShippingCharge = shippingChargeModel.ShippingCharge;
modelFromDb.ModifyDate = DateTime.Now;
_catShippingService.Update(modelFromDb);
return new NullJsonResult();
}
This is my Kendo Grid :
function loadKendo() {
var dataNew = {};
$("#shippingCharge-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("GetDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
},
update: {
url: "#Html.Raw(Url.Action("UpdateDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
//data: addAntiForgeryToken
},
destroy: {
url: "#Html.Raw(Url.Action("DeleteDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
}
,
parameterMap: function (data, operation) {
if (operation === "update") {
dataNew.Id = data.Id;
dataNew.CategoryId = data.CategoryId;
dataNew.ShippingCharge = data.ShippingCharge;
dataNew.SaleStartDate = stringToTimestamp(data.SaleStartDate.toUTCString());
dataNew.SaleEndDate = stringToTimestamp(data.SaleEndDate.toUTCString());
dataNew.SchoolEmail = data.SchoolEmail;
return { ShippingChargeModel: dataNew };
}
return data;
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
fields: {
//ProductId: { editable: false, type: "number" },
CategoryId: { editable: false, type: "string" },
CategoryName: { editable: false, type: "string" },
ShippingCharge: { editable: true, type: "number" },
SaleStartDate: { editable: true, type: "date", format: "{0:dd/MMM/yyyy HH:mm}"},
SaleEndDate: { editable: true, type: "date", format: "{0:dd/MMM/yyyy HH:mm}"},
SchoolEmail: { editable:true, type: "string" }
}
}
},
requestEnd: function (e) {
if (e.type == "update") {
this.read();
}
if (e.type == "cancel") {
this.cancelChanges();
}
},
error: function (e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
numeric: false,
previousNext: false,
info: false,
pageSizes: [#(gridPageSizes)]
},
editable: {
confirmation: "#T("Admin.Common.DeleteConfirmation")",
mode: "inline"
},
scrollable: false,
columns: [
{
field: "CategoryName",
title: "CategoryName",
width: 300
},
{
field: "ShippingCharge",
title: "Shipping Charge",
width: 100,
encoded: false
}
,
{
field: "SchoolEmail",
title: "Email",
width: 200,
encoded: false
}
,
{
field: "SaleStartDate",
title: "Sale Start Date",
width: 200,
encoded: false,
type: "datetime",
format: "{0:dd/MMM/yyyy HH:mm}",
template: "#= kendo.toString(kendo.parseDate(SaleStartDate, 'yyyy-MM-dd'), 'dd/MMM/yyyy') #",
editor: dateTimeEditor
},
{
field: "SaleEndDate",
title: "Sale End Date",
width: 200,
encoded: false,
type: "datetime",
format: "{0:dd/MMM/yyyy HH:mm}",
template: "#= kendo.toString(kendo.parseDate(SaleEndDate, 'yyyy-MM-dd'), 'dd/MMM/yyyy') #",
editor: dateTimeEditor
}, {
command: [
{
name: "edit",
text: {
edit: "#T("Admin.Common.Edit")",
update: "#T("Admin.Common.Update")",
cancel: "#T("Admin.Common.Cancel")"
}
}
, {
name: "destroy",
text: "#T("Admin.Common.Delete")"
}
],
width: 200
}
]
});
}
Please help me out. Any sort of insight will do ...
I want to fetch data from server into a datatable in asp.net mvc5. I have my own datatable template which I want to customize but I couldn't fetch the data. The ajax call plus datatable itself is like below:
var DatatableRemoteAjaxDemo = function() {
//== Private functions
// basic demo
var demo = function() {
var datatable = $('.m_datatable').mDatatable({
// datasource definition
data: {
type: 'remote',
source: {
read: {
// sample GET method
method: 'GET',
url: '/ActionLinks/getActionLinks',
map: function(raw) {
// sample data mapping
var dataSet = raw;
if (typeof raw.data !== 'undefined') {
dataSet = raw.data;
}
return dataSet;
},
},
},
pageSize: 10,
saveState: {
cookie: true,
webstorage: true,
},
serverPaging: true,
serverFiltering: true,
serverSorting: true,
},
// layout definition
layout: {
theme: 'default', // datatable theme
class: '', // custom wrapper class
scroll: false, // enable/disable datatable scroll both horizontal and vertical when needed.
footer: false // display/hide footer
},
// column sorting
sortable: true,
pagination: true,
toolbar: {
// toolbar items
items: {
// pagination
pagination: {
// page size select
pageSizeSelect: [10, 20, 30, 50, 100],
},
},
},
search: {
input: $('#generalSearch'),
},
// columns definition
columns: [
{
field: 'ActionLinkId',
title: '#',
sortable: false, // disable sort for this column
width: 40,
selector: false,
textAlign: 'center',
}, {
field: 'ActionText',
title: 'Quiz Title',
// sortable: 'asc', // default sort
filterable: false, // disable or enable filtering
width: 150,
}, {
field: 'ActionDescription',
title: 'Quiz Description',
width: 150,
}, {
field: 'Category',
title: 'Category',
}, {
field: 'SmallImageURL',
title: 'Small Image URL',
width: 100,
}, {
field: 'LargeImageURL',
title: 'Large IMG URL',
width: 100,
},{
field: 'DateCreated',
title: 'CreationDate',
sortable: 'asc',
type: 'date',
format: 'MM/DD/YYYY',
}],
});
var query = datatable.getDataSourceQuery();
$('#m_form_status').on('change', function() {
// shortcode to datatable.getDataSourceParam('query');
var query = datatable.getDataSourceQuery();
query.Status = $(this).val().toLowerCase();
// shortcode to datatable.setDataSourceParam('query', query);
datatable.setDataSourceQuery(query);
datatable.load();
}).val(typeof query.Status !== 'undefined' ? query.Status : '');
$('#m_form_type').on('change', function() {
// shortcode to datatable.getDataSourceParam('query');
var query = datatable.getDataSourceQuery();
query.Type = $(this).val().toLowerCase();
// shortcode to datatable.setDataSourceParam('query', query);
datatable.setDataSourceQuery(query);
datatable.load();
}).val(typeof query.Type !== 'undefined' ? query.Type : '');
$('#m_form_status, #m_form_type').selectpicker();
};
return {
// public functions
init: function() {
demo();
},
};
}();
jQuery(document).ready(function() {
DatatableRemoteAjaxDemo.init();
});
My JsonResult code to fetch data from database is like below:
public JsonResult getActionLinks()
{
var actionlinks = db.ActionLinks.OrderBy(i => i.ActionLinkId).ToList();
return Json(new { data = actionlinks }, JsonRequestBehavior.AllowGet);
}
I debugged it the call hits the URL but I can't fetch the data into my datatable. It says 304 error. Please help.
I have a kendo grid that is edited inline. One of the fields should be edited selecting an element from a list, but the list must have a hierarchical structure (would be nice be able of filter that list). I was thinking in use a kendo treeview as editor for that field but I haven't found any way to accomplish this. I tried make a custom editor template (using columns.Bound(s => s.FieldId).EditorTemplateName("_TreeEditorTemplate")) that render the treeview, but the treeview is not an input and is not selectable. I also thinked in make an editor that use a kendo dropdownlist with the tree inside but this is no currently supported by kendo. Any ideas???
Have you looked at the sample on the Kendo site: https://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/Editing/use-treeview-as-grid-editor
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "//demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
UnitPrice: { type: "number", validation: { required: true, min: 1 } },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
},
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
edit: function (e) {
//checking if a cell from the Test column is opened for editing
var dummyInput = e.container.find("input[name='test']");
if (dummyInput.length > 0) {
var treeView = $(e.container).find(".treeViewEditor").data("kendoTreeView");
var originalItem = treeView.findByText(dummyInput.val());
if (originalItem != null) {
// Select the item based on the field value
treeView.select(originalItem);
}
}
},
navigatable: true,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: [
"ProductName",
{
field: "test", title: "Test", width: 120,
editor: function (container, options) {
var input = $("<input class='tveInput'/>");
input.attr("name", options.field);
var tvDiv = $("<div class='treeViewEditor'></div>");
$(tvDiv).kendoTreeView({
animation: false,
dataSource: [
{
text: "foo1"
},
{
text: "foo2",
items: [
{ text: "bar" },
{ text: "bar1" },
{ text: "bar2" }
]
}
]
});
var treeView = $(tvDiv).data("kendoTreeView");
$(tvDiv).find(".k-in").mousedown(function (e) {
var clickedNode = $(e.toElement).closest("[role=treeitem]");
var dataItem = treeView.dataItem(clickedNode);
var dummyInput = clickedNode.closest("[role=gridcell]").find("input[name='test']");
dummyInput.val(dataItem.text);
dummyInput.trigger("change");
});
tvDiv.appendTo(container);
input.appendTo(container);
}
},
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: 120 },
{ field: "UnitsInStock", title: "Units In Stock", width: 120 },
{ field: "Discontinued", width: 120 },
{ command: "destroy", title: " ", width: 150 }],
editable: true
});
});
</script>
</div>
<style>
.tveInput {
display: none;
}
</style>
i got a view with a jquery datatable, i want on a single button to repopulate the data from the table instantly with another Json list or whatever array he received from the controller.
This is the code in my view :
$.ajax({
type: "GET",
url: "EmpTruck/getJson/",
data: { search: station },
dataType: "Json",
error: function (xhr, status, error) {
alert(error);
},
success: function (json) {
alert(json.aaData);
var table = $(".dynamicTableEmployee").dataTable();
table.fnClearTable();
table.LoadDataRow(json);
}
});
This is the code from controller :
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult getJson()
{
List<Employees> list = new List<Employees>();
list = db.Employees.Where(c => c.Station.Equals("ATL")).ToList();
return this.Json(list, JsonRequestBehavior.AllowGet);
}
This code only clear the datatable.
I have set a breakpoint to see if there is something in the Json array and there is.
I don't know how to populate the datatable from the json array, do i need to serialize it ? Do the json need to be the same size as the datatable?
Thanks
If you are just looking to reload the data you can use the fnReloadAjax() API plug-in: http://datatables.net/plug-ins#api_fnReloadAjax
If you want to completely alter the table like change columns etc... I'd just nuke the old one and replace it with the new. Just paste the code into your script (before you initialise you table!), then whenever you want to reload the data, call fnReloadAjax() on the table object.
This example might help: http://datatables.net/examples/example_plugin_api.html
(from http://www.datatables.net/forums/discussion/52/load-new-data-via-ajax/p1)
<link href="#Url.Content("~/Content/Table.css")" rel="stylesheet" type="text/css" />
#section scripts
{
<script src="#Url.Content("~/Scripts/ datatable.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/test.js")" type="text/javascript"> </script>
}
<div id="tabs-SecDeal" style=" background-color: white">
<table id="secdeal" class="display">
<thead>
<tr>
<th style="background-color: #990033">col1</th>
<th style="background-color: #990033"> col2</th>
<th style="background-color: #990033"> col3 </th>
<th style="background-color: #990033"> col4</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4" class="dataTables_empty"></td>
</tr>
</tbody>
</table>
</div>
$(function () {
Loadtestview();
function Loadtestview () {
var divSecTable = $('#secdeal');
oSecTable = divSecTable.dataTable({
"processing": true,
"serverSide": true,
"aaSorting": [1, 'asc'],
"info": true,//localtable.bInfo,
"autoWidth": false,//localtable.AutoWidth,
"scrollY": 700,
"scrollX": "150%",
"scrollCollapse": true,
'destroy': true,
"pagingType": "full_numbers",
'lengthChange': false,
"searching": false,
'sAjaxSource': '../ReportsMvc/GetSecuritizationDeal',
"iDisplayLength": 100,
"columns": [
{ "targets": 0,"data":"col1","title":"col1", "className": "center textNoWrap" },
{ "targets": 1,"data":"col2","title":"col2", "className": "center textNoWrap" },
{ "targets": 2,"data":"col3","title":"col3", "className": "center textNoWrap" },
{ "targets": 3,"data":"col4","title":"col4", "className": "center textNoWrap" },
],
'fnServerData': function (sSource, aoData, fnCallback) {
aoData.push({ "name": "rgid", "value": $("#ddlBatchdate").val() });
$.get(sSource, aoData, function (rsp) {
fnCallback(rsp);
});
},
"fnInitComplete": function () {
new $.fn.dataTable.FixedColumns(oSecTable, { leftColumns: 4 });
}
});
}
});
[HttpGet]
public JsonResult GetSecuritizationDeal(jQueryDataTableParamModel param)
{
if (param.rgid <= 0)
{
return Json(new
{
sEcho = "1",
iTotalRecords = 0,
iTotalDisplayRecords = 0,
aaData = (IEnumerable<SecDealDatacs>)new List<SecDealDatacs>()
},
JsonRequestBehavior.AllowGet);
}
try
{
//No session cache for reports page!!!
List<SecDealDatacs> listObj = _bao.GetSecuritizationDeal(param.rgid);
if (listObj == null)
throw new HttpException(500, "Data Server Errors...");
int totalRecords = listObj.Count();
//Pagenation
IEnumerable<SecDealDatacs> listObjDisplay = listObj
.Skip(param.iDisplayStart)
.Take(param.iDisplayLength);
var result = listObjDisplay.Select((o, index) => new
{
o.col1,
o.col2,
col3= o.col3.ToString("#,#"),
col4=o. col4.ToString("0.0000"),
}).ToList();
var listObj1 = result;
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = totalRecords,
iTotalDisplayRecords = totalRecords,
aaData = result
},JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
//log error into DB and File
throw new HttpException(500, ex.Message);
}
}
$(function () {
Loadtestview();
function Loadtestview () {
var divSecTable = $('#secdeal');
oSecTable = divSecTable.dataTable({
"processing": true,
"serverSide": true,
"aaSorting": [1, 'asc'],
"info": true,//localtable.bInfo,
"autoWidth": false,//localtable.AutoWidth,
"scrollY": 700,
"scrollX": "150%",
"scrollCollapse": true,
'destroy': true,
"pagingType": "full_numbers",
'lengthChange': false,
"searching": false,
'sAjaxSource': '../ReportsMvc/GetSecuritizationDeal',
"iDisplayLength": 100,
"columns": [
{ "targets": 0,"data":"col1","title":"col1", "className": "center textNoWrap" },
{ "targets": 1,"data":"col2","title":"col2", "className": "center textNoWrap" },
{ "targets": 2,"data":"col3","title":"col3", "className": "center textNoWrap" },
{ "targets": 3,"data":"col4","title":"col4", "className": "center textNoWrap" },
],
'fnServerData': function (sSource, aoData, fnCallback) {
aoData.push({ "name": "rgid", "value": $("#ddlBatchdate").val() });
$.get(sSource, aoData, function (rsp) {
fnCallback(rsp);
});
},
"fnInitComplete": function () {
new $.fn.dataTable.FixedColumns(oSecTable, { leftColumns: 4 });
}
});
}
});