jsgrid need functionality to upload and show image - file-upload

I am using jsGrid for showing data from database. But I am stuck with a problem.
All text field or select field are rendering correctly. But I need to add a custom field with functionality to add image on edit (when no image added) a row and show image on the field while page load using jsGrid. I searched the web but not find any solution to solve my issue.

This is how it could be implemented:
var data = [
{ Name: "John", Img: "http://placehold.it/250x250" },
{ Name: "Jimmy", Img: "http://placehold.it/250x250" },
{ Name: "Tom", Img: "http://placehold.it/250x250" },
{ Name: "Frank", Img: "http://placehold.it/250x250" },
{ Name: "Peter", Img: "http://placehold.it/250x250" }
];
$("#dialog").dialog({
modal: true,
autoOpen: false,
position: {
my: "center",
at: "center",
of: $("#jsgrid")
}
});
$("#jsgrid").jsGrid({
autoload: true,
width: 350,
filtering: true,
inserting: true,
controller: {
loadData: function(filter) {
return !filter.Name
? data
: $.grep(data, function(item) { return item.Name.indexOf(filter.Name) > -1; });
// use ajax request to load data from the server
/*
return $.ajax({
method: "GET",
url: "/YourUrlToAddItemFilteringScript",
data: filter
});
*/
},
insertItem: function(insertingItem) {
var formData = new FormData();
formData.append("Name", insertingItem.Name);
formData.append("Img[]", insertingItem.Img, insertingItem.Img.name);
return $.ajax({
method: "post",
type: "POST",
url: "/YourUrlToAddItemAndSaveImage",
data: formData,
contentType: false,
processData: false
});
}
},
fields: [
{
name: "Img",
itemTemplate: function(val, item) {
return $("<img>").attr("src", val).css({ height: 50, width: 50 }).on("click", function() {
$("#imagePreview").attr("src", item.Img);
$("#dialog").dialog("open");
});
},
insertTemplate: function() {
var insertControl = this.insertControl = $("<input>").prop("type", "file");
return insertControl;
},
insertValue: function() {
return this.insertControl[0].files[0];
},
align: "center",
width: 120
},
{ type: "text", name: "Name" },
{ type: "control", editButton: false }
]
});
Checkout the working fiddle http://jsfiddle.net/tabalinas/ccy9u7pa/16/
According issue on GitHub: https://github.com/tabalinas/jsgrid/issues/107

Related

How to display a List of object in Kendo Grid in jquery?

I am working on a project in which I need to display List of objects in Kendo Grid.
below is the code for data binding.
$("#GridProperty").kendoGrid({
dataSource: {
transport: {
read: {
dataType: "json",
url: $_BindPropertyData,
data: { "LegalEntityId": LegalEntityId, "DatasetId": DatasetId },
async: true,
}
},
schema: {
model: {
fields: {
GeoId: { type: "int" },
GeoDescription: { type: "string" },
GeoAbbreviation: { type: "string" },
//ComponentDesc: { type: "string", from: "CompModelList.ComponentDesc" },
Id: { type: "int" },
Amount1: { type: "decimal", from: "CompModelList.SaDataModel.Amount1" },
Amount2: { type: "decimal"}
//lstcompModel: {type: ""}
}
}
},
},
noRecords: {
template: "<p style='margin-top:5px;'>There are currently no items available<p>"
},
height: 525,
reorderable: true,
groupable: true,
sortable: true,
filterable: true,
resizable: true,
columnMenu: true,
selectable: "row",
dataBound: function () {
},
columns: Columns
});
Description :
I am returning list of objects as json from my Action . but i am not able to bind the list of objects in kendo grid.
I am breaking my head for last four days. Please help.
Thanks

Passing data in view model to controller via kendo grid

So far, I'm just trying to instantiate my kendogrid and passing through values from my view model. I got the following piece of code from Telerik's documentation for vb.net. The thing is, an exception is thrown from .Grid ->
"Type parameter for public overridable overloads function grid(of T as a class) as a gridbuilder(of t) cannot be inferred"
Html.Kendo().Grid().Name("kendogrid")
I'm not sure what this error means and I don't know how to go about fixing it.
View
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "TestAjax",
dataType: "json",
type: "GET",
},
update: {
url: "update",
dataType: "json",
type: "POST"
},
create: {
url: "CreateInvoiceRecord",
dataType: "json",
type: "GET",
},
parameterMap: function (options, operation) {
console.log(operation);
console.log(options);
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "itemID",
fields: {
ItemName: { type: "string" },
Amount: { type: "number", editable: false, validation: { required: true } },
ProductLine: { type: "string" },
Status: { type: "string" },
}
}
},
aggregate: [{ field: "Amount", aggregate: "sum" }
]
});
$("#kendogrid").kendoGrid({
DataSource: dataSource,
pageable: true,
height: 550,
toolbar: ["create", "save"],
columns: [
{ field: "ItemName", title: "Item", width: "150px" },
{ field: "Amount", title: "Amount", format: "{0:c}", width: "100px", aggregates: ["sum"], footerTemplate: "Total Amount: #=sum#" },
{ field: "ProductLine", title: "Product Line", width: "150px", editor: productLineDropDownEditor},
{ field: "Status", title: "Status", width: "150px", editor: statusDropDownEditor },
{ command: "Update", title: "Update" , width:"150px"}],
editable: true
});
});
Model
Public Class MyViewModel
Public Property id As String
Public Property id2 As String
End Class
The VB grid syntax from http://docs.telerik.com/kendo-ui/aspnet-mvc/vb#grid
is:
Html.Kendo().Grid(Of YourViewModelClassThatYouWantToBindTheGridTo)() _
.Name("grid") _
...additional configuration.
You are missing the part where you tell the grid what type of object you are binding to(the "Of NameOfYourClass" part.
You should post your whole grid definition.
Also...C# syntax is sooooo much cleaner(I know that's not helpful).
Edit
OK, so this question isn't about the correct VB.NET Razor syntax anymore....
This is how you get "extra" data passed to the controller methods from a dataSource: you use the dataSource.transport.read.data configuration (http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-transport.read.data)
Using an object:
transport: {
read: {
url: "TestAjax",
dataType: "json",
type: "GET",
data: {
parameterToPassToReadAction: valueYouWantToPassToReadAction
}
},
Using a function:
transport: {
read: {
url: "TestAjax",
dataType: "json",
type: "GET",
data: extraDataFunction
},
function extraDataFunction () {
return {
parameterToPassToReadAction: valueYouWantToPassToReadAction
};
}
Where parameterToPassToReadAction is the name of the parameter in your server method and valueYouWantToPassToReadAction is the value you want it to be...which is stored where ever you stored it when the page loaded. If it is in a ViewModel of your vbhtml file and your javascript is in the script block of that same file, the syntax will be something like:
function extraDataFunction () {
return {
parameterToPassToReadAction: #Model.FieldYouWantToSend
};
}
But it is not clear where you have this value stored.
Finally got what I wanted working using a hack for create and then ajax for read. Not totally sure why this works the way it does so I'll need to look into it some more. I needed to pass parameters to controllers that are connected to kendogrid - specifically the read and create operations. I created a view model to store the values that I obtained from my Index controller and then used the view model to pass the values from kendogrid to the read and create operation controllers. For some reason, I was only able to pass parameters to the read operation using ajax.
Note: Still not the best solution. It calls readData controller twice and I don't want that.
Javascript
<Script>
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "readData",
dataType: "json",
type: "GET",
},
create: {
url: "CreateInvoiceRecord?trxid=#Model.id2&bcid=#Model.id",
dataType: "json",
type: "GET",
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "itemID",
fields: {
ItemName: { type: "string" },
Amount: { type: "number", validation: { required: true } },
ProductLine: { type: "string" },
Status: { type: "string" }
}
}
},
aggregate: [{ field: "Amount", aggregate: "sum" }]
});
$("#kendogrid").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
height: 550,
toolbar: ["create", "save"],
columns: [
{ field: "ItemName", title: "Item", width: "150px" },
{ field: "Amount", title: "Amount", format: "{0:c}", width: "100px", aggregates: ["sum"], footerTemplate: "Total Amount: #=sum#" },
{ field: "ProductLine", title: "Product Line", width: "150px", editor: productLineDropDownEditor},
{ field: "Status", title: "Status", width: "150px", editor: statusDropDownEditor },
{ command: "Update", title: "Update" , width:"150px"}],
editable: true
});
});
function productLineDropDownEditor(container, options) {
$('<input required name="' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
valuePrimitive: true,
dataTextField: "name",
dataValueField: "name",
dataSource: {
transport: {
read: {
url: "/Customs/getProdLines",
dataType: "json"
}
},
schema: {
data: "Data",
model: {
fields: {}
}
},
}
});
}
function statusDropDownEditor(container, options) {
var data = [
{ text: "Active", value: "1" },
{ text: "Paid", value: "2" },
{ text: "Cancelled", value: "3" }
]
$('<input required name="' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
valuePrimitive: true,
dataTextField: "text",
dataValueField: "value",
autobind: false,
dataSource: data
});
}
//function testAjax() {
//}
//data: { 'name': ItemName, 'amount': Amount, 'prodline': ProductLine, 'status': Status },
$.ajax({
type: "Get",
data: { id: "#Model.id", id2:"#Model.id2" },
url: "readData/",
dataType: "json",
success: function (itemList) {
console.log(itemList);
}
});
</script>
Model
Public Class MyViewModel
Public Property id As String
Public Property id2 As String
End Class

Event that is taking place after inline edit

I have jqgrid, which sends row's data to another view (MVC4) when row is selected. But when I edit row's info (I'm using inline edit) this view doesn't changed. And I can't find event that is taking place after inline edit. This is js, what should I change to change my view after row editing
$(function () {
$("#GridTable").jqGrid({
url: "/Goods/GoodsList",
editurl: "/Goods/Edit",
datatype: 'json',
mtype: 'Get',
colNames: ['GoodId', 'Имя', 'Цена'],
colModel: [
{ key: true, hidden: true, name: 'GoodId', index: 'GoodId', editable: true },
{
key: false, name: 'GoodName', index: 'GoodName', editable: true, sortable: true,
editrules: {
required: true, custom: true, custom_func: notATag
}
},
{
key: false, name: 'Price', index: 'Price', editable: true, sortable: true, formatter: numFormat,
unformat: numUnformat,
//sorttype: 'float',
editrules: { required: true, custom: true, custom_func: figureValid}
}, ],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 25, 50, 100],
height: '100%',
viewrecords: true,
caption: 'Список товаров',
sortable: true,
emptyrecords: 'No records to display',
cellsubmit : 'remote',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
//to get good's full view when row is selected
onSelectRow:
function () {
var myGrid = $('#GridTable'),
selRowId = myGrid.jqGrid('getGridParam', 'selrow'),
celValue = myGrid.jqGrid('getCell', selRowId, 'GoodId');
$.ajax({
url: "/Goods/DetailInfo",
type: "GET",
data: { id: celValue }
})
.done(function (partialViewResult) {
$("#goodDetInfo").html(partialViewResult);
});
},
//to change good's full view after row deleting
loadComplete: function(data){
var myGrid = $('#GridTable'),
selRowId = myGrid.jqGrid('getGridParam', 'selrow'),
celValue = myGrid.jqGrid('getCell', selRowId, 'GoodId');
$.ajax({
url: "/Goods/DetailInfo",
type: "GET",
data: { id: celValue }
})
.done(function (partialViewResult) {
$("#goodDetInfo").html(partialViewResult);
});
},
autowidth: true,
multiselect: false
}).navGrid('#pager', { edit: false, add: true, del: true, search: false, refresh: true },
{
// edit options
zIndex: 100,
url: '/Goods/Edit',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
var myGrid = $('#GridTable'),
selRowId = myGrid.jqGrid('getGridParam', 'selrow'),
celValue = myGrid.jqGrid('getCell', selRowId, 'GoodId');
$.ajax({
url: "/Goods/DetailInfo",
type: "GET",
data: { id: celValue }
})
.done(function (partialViewResult) {
$("#goodDetInfo").html(partialViewResult);
});
}
},
{
// add options
zIndex: 100,
url: "/Goods/Create",
closeOnEscape: true,
closeAfterAdd: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
// delete options
zIndex: 100,
url: "/Goods/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);
}
}
});
$('#GridTable').inlineNav('#pager', {
edit: true,
add: false,
del: false,
cancel: true,
editParams: {
keys: true,
afterSubmit: function (response) {
if (response.responseText) {
alert(response.responseText);
}
var myGrid = $('#GridTable'),
selRowId = myGrid.jqGrid('getGridParam', 'selrow'),
celValue = myGrid.jqGrid('getCell', selRowId, 'GoodId');
$.ajax({
url: "/Goods/DetailInfo",
type: "GET",
data: { id: celValue }
})
.done(function (partialViewResult) {
$("#goodDetInfo").html(partialViewResult);
});
}
},
});
});
The properties and callback function of editParams parameter of inlineNav can be found here. What you need is probably aftersavefunc or successfunc instead of afterSubmit, which exist only in form editing method (see here). The parameters of aftersavefunc or successfunc callbacks are described here (as parameters of saveRow), but the parameters depend on the version of jqGrid, which you use and from the fork of jqGrid (free jqGrid, commercial Guriddo jqGrid JS or an old jqGrid in version <=4.7). I develop free jqGrid fork and I would recommend you to use the current (4.13.3) version of free jqGrid.

Kendo Grid - Create Transport, ID not set

See this question with no response: Kendo Grid does not update the grid with newly created id after creation
When creating a new link, my method is hit, and I return the full item with the ID set:
[HttpPost]
public JsonResult Create(string LINK_TEXT, string HREF, string CATEGORY)
{
var link = new LinkDTO {LINK_TEXT = LINK_TEXT, HREF = HREF, CATEGORY = CATEGORY};
var insertedLink = LinkService.Create(link);
return Json(new[] {insertedLink}, JsonRequestBehavior.AllowGet);
}
In the client, the response is:
{"ID":86,"LINK_TEXT":"Test2","HREF":"http://www.google.com","CATEGORY":"Category1"}
I've also tried only returning the ID:
{"ID":86}
Upon inspection of the kendo data:
CATEGORY: "Category1"
HREF: "http://www.google.com"
ID: 0
LINK_TEXT: "Test2"
_events: Object
dirty: false
id: 0
parent: function (){return r}
uid: "4739cc3d-a270-44dd-9c63-e9d378433d98"
The ID is 0. When I try to edit this link it thinks it is new, so it calls create again, thus duplicating the link.
Here is my grid definition:
$(document).ready(function () {
$("#link-results").kendoGrid({
dataSource: {
transport: {
create: {
url: '#Url.Action("Create", "Link")',
dataType: 'json',
type: 'POST'
},
read: {
url: '#Url.Action("Read", "Link")',
dataType: 'json',
type: 'GET',
data: {
CATEGORY: '#Model.CategoryName'
}
},
update: {
url: '#Url.Action("Update", "Link")',
dataType: 'json',
type: 'POST',
data: {
CATEGORY: '#Model.CategoryName'
}
},
destroy: {
url: '#Url.Action("Delete", "Link")',
dataType: 'json',
type: 'POST'
}
},
pageSize: 10,
schema: {
data: "Links",
total: "ResultCount",
model: {
id: "ID",
fields: {
ID: {type: "number"},
LINK_TEXT: { type: "string", required: true },
HREF: { type: "string", defaultValue: "", validation: { required: true } },
CATEGORY: { type: "string", defaultValue: '#Model.CategoryName', editable: false }
}
}
}
},
pageable: true,
toolbar: ["create"],
columns: [
{ field: "ID", hidden: true },
{ field: "LINK_TEXT", title: "Name", width: "40px"/*, template: "<a href='#=HREF#'>#=LINK_TEXT#</a>"*/ },
{ field: "HREF", title: "Link", width: "100px",filterable: false/*, template: "<a href='#=HREF#'>#=HREF#</a>"*/ },
{ field: "CATEGORY", title: "Category", width: "50px", filterable: false},
{
command: [
{ name: "edit", text: "" },
{ name: "destroy", text: "" }
],
title: " ",
width: "70px"
}
],
editable: "inline",
filterable: true,
sortable: "true"
});
I added the ID: {type: "number"}, part in an attempt to get this to work, I realize I should not need this in my fields definition since it is defined with id: "ID".
I figured out what the problem was, here is the text from another answer I provided regarding the same issue (see Kendo Grid does not update the grid with newly created id after creation):
I've had the same problem and think I may have found the answer. If in the schema you define the object that holds the results, you must return the result of the created link in that same object. Example:
schema: {
data: "data",
total: "total", ....
}
Example MVC method:
public JsonResult CreateNewRow(RowModel rowModel)
{
// rowModel.id will be defaulted to 0
// save row to server and get new id back
var newId = SaveRowToServer(rowModel);
// set new id to model
rowModel.id = newId;
return Json(new {data= new[] {rowModel}});
}

How to display Extjs.Ajax response in Grid

I have posted the form data using Ext.Ajax.request and I get the JSON in response. Now I want to display this JSON in grid. How can I do this? Please help me out in this.
Following is my code:
var simple = new Ext.FormPanel({
labelWidth: 85,
frame:true,
title: 'Test on Demand',
bodyStyle:'padding:10px 10px;',
width: 280,
defaults: {width: 250},
defaultType: 'textfield',
items: [ combo, myText],
buttons: [{
text: 'Start',
handler: function() {
var rtu_id = combo.getValue();
var testplanid = myText.getValue();
Ext.Ajax.request({
url : 'http://localhost/rtu_ems_extjs/lib/action',
method: 'POST',
headers: { 'Content-Type': 'application/json'}, params : { "action" : "rtu_request" },
jsonData: {
"rtu_id" : rtu_id,
"testplanid" : testplanid
},
success: function (response) {
var jsonResp = Ext.decode(response.responseText);
Ext.Msg.alert("Info",jsonResp.Type);
},
failure: function (response) {
var jsonResp = Ext.decode(response.responseText);
Ext.Msg.alert("Error",jsonResp.error);
}
});
}
}, {
text: 'Reset',
handler: function() {
simple.getForm().reset();
}
}]
});
simple.render(document.body);
I want to display 'jsonResp' in grid.