I am using jqGrid with ASP.NET MVC 3 and Razor.
I am looking to add 2 columns to the jqGrid along with the rest of the columns.
The columns I want to add are
Edit
Delete
These columns value I want to be ActionLink.
How do I add an ActionLink to a Column of a JqGrid ?
Please guide me on this.
Update 1: with help from #user1534482 I tried this but did not work
colModel: [
...
{ name: 'Open', formatter: 'prepareLinks' },
...
],
function prepareLinks(cellvalue, options, rowObject) {
return "#Html.ActionLink("Open this","Test")";
}
javascript error message :
SyntaxError: missing ; before statement
[Break On This Error]
return "Open this";
SomeController (line 92, col 41)
You should take a look at showlink predefined formatter.
There is no code in your question so I don't know how complex your scenario is, but in general code like this should be enough:
<script type="text/javascript">
jQuery("#gridId").jqGrid({
colNames: [..., 'Edit', 'Delete'],
colModel: [
...
{name:'EditAction', formatter:'showlink', formatoptions: { baseLinkUrl: '#Url.Action("Edit")' } },
{name:'DeleteAction', formatter:'showlink', formatoptions: { baseLinkUrl: '#Url.Action("Delete")' } }
],
...
});
</script>
The row id will be added automatically (you can control how with idName option). If you need to pass some additional parameters take a look at addParam option in the documentation.
UPDATE
For clarification on how the final link is generated, you can use this formula:
"<a " + ((op.target) ? "target=" + op.target : "") + " href=\"" + op.baseLinkUrl + op.showAction + "?" + op.idName + "=" + rowId + op.addParam + "\">" + cellvalue + "</a>"
Where op is the formatoptions object and cellvalue is the value for the column from data you have pasted to the jqGrid.
u can use ur own formater like
colModel: [
{ name: 'colname', formatter: linkbuilder },
],
and
and add function
function linkbuilder(cellval, opts, rwdat, _act) {
return "#Htm.ActionLink()";
}
Thanks to #tpeczek and #user1534482
I finally got the solution,
colModel: [
...
{ name: 'Open',
formatter: function (cellvalue, options, rowObject) {
return '' + "Open" + '';
}
},
...
],
Related
editable:true,edittype: "select",
editoptions: {
dataUrl : '/test.do?cd=abc',
cacheUrlData: true,
buildSelect : function(data) {
var data = ($.parseJSON(data)).list;
var s='<select>';
for(d of data){
s += '<option value=' + d.comCd + '>' + d.comNm + '</option>';
}
s += '</select>';
return s;
},
},
When I checked the data after saving,
it contained d.comNm, which is text, not d.comCd, which is the value of the option.
var gridData = grid.jqGrid('getRowData');
console.log(gridData);
It is jqgrid 5.2.1 version, and it is an old project using java 1.7.
Can someone please help me?
Expected this
Result
I have no problem with it appearing on the grid.
The biggest problem is that the value is not stored in the data (getRowData).
As far as understand you want to display in grid the value, but when inline edit if on, you display select with value=> text on it, but when saved to save and display the value.
To do this the trick is to define custom formatter only, which return the cellvalue. For that field in colModel do
colModel : [
....
{
name: 'name1',
editable:true,
edittype: "select",
editoptions : {...},
formatter : function(cellval) {
return cellval;
}
}
...
]
I'm using a DropDownList for a field that I'm editing in a Kendo UI grid popup, and though validation tooltips show up without problems, they don't disappear once the input has been corrected.
I'm creating the DropDownList like this:
function serviceDropDownEditor(container, options) {
$('<input data-bind="value:' + options.field + '" data-for="' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
optionLabel: "--- select a service ---",
dataTextField: "name",
dataValueField: "id",
dataSource: window.services, // an array I've already fetched from my DB
});
}
I apply this function to the field service_id when I define the data source, like this:
columns: [
{ field: "service_id",
title: "Service",
editor: serviceDropDownEditor,
template: "#= getServiceName(service_id) #" // display the name from the id
},
To make sure there's a place to put the validation message, I use the suggestion on this page and append a placeholder span below the DropDownList during the edit event:
edit: function(e) {
var grid = $("#grid").data("kendoGrid")
var container = grid.editable.element
var service_container= container.find("[data-container-for=service_id]")
service_container.append('<span class="k-invalid-msg", data-for="#= field #">')
},
When there's a server-side error that refers to this field (service_id), I find the placeholder that I created in the edit event and replace it with the actual message, like this:
var placeholder = container.find("[data-for=" + field + "].k-invalid-msg")
placeholder .replaceWith(validationMessageTmpl({ field: field, message: errors[field] }))
The validation message template contains the same classes and data-for attribute as the placeholder.
It works great when displaying an error for the DropDownList, but when I correct the error (and introduce another one on the same form, so the popup stays up), the original error doesn't disappear.
So... how do validation tooltips get cleared, and what do I need to do? Clear this one manually in an event?
Try to manually clear errors on drop down change eg:
function serviceDropDownEditor(container, options) {
$('<input data-bind="value:' + options.field + '" data-for="' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
optionLabel: "--- select a service ---",
dataTextField: "name",
dataValueField: "id",
dataSource: window.services, // an array I've already fetched from my DB
select: function (ev) {
var validatable = container.editable.validatable;
if (validatable) {
var dataItem = this.dataItem(ev.item.index());
if (dataItem === null || dataItem === undefined || dataItem.text == " " || dataItem.text == " ") {
// force validation is empty (simulate required)
validatable.validate();
} else {
// hide all error messages if not empty
validatable.hideMessages();
}
}
}
});
}
I have a grid and I'm using PHP and JSON. I'm using ondblClickRow to do inline editing. The thing that I need is: when I double click in a field, I want the content of this field will be select. I'm sorry to ask about this, but I didn't find this... when I search it on Google I just find examples of select row and this issues.
I recommend you to look this answer and another one. Probably modification of the code from the last answer to the web browser which you use will get your the solution of your problem.
If you want a single cell to be focused after inline edit mode is enabled, try this:
ondblClickRow: function (rowId, rowIndex, columnIndex) {
var grid = $('#mygrid');
grid.editRow(rowId, true, function() {
var colModel = grid.getGridParam('colMode');
var colName = colModel[colIndex].name;
var input = $('#' + rowId + '_' + colName);
input.get(0).focus();
});
}
}
Found the code here:
http://www.trirand.com/blog/?page_id=393/help/setting-focus-on-a-cell-after-entering-edit-mode/
If you have specific columns in a grid when you click on it should select its contents, then in your colmodel add this code to each column:
{
name: 'TEXT_BOX',
index: 'TEXT_BOX',
label: 'Notes',
width: 100,
align: 'left',
sortable: false,
hidden: false,
dataEvents: [ { type: 'click', data: { i: 7 }, fn: function(e) { e.target.select(); } }]
}
dataEvents will select the text in the input field when you click on it.
// Text will get Selected of cell when inline editing
$('#gridTableObj').jqGrid({
....
..
afterEditCell : function(rowid, cellname, value, iRow, iCol){
$('#'+rowid+'_'+cellname).select(); // with this the edited cell value will be selected.
}
...
..
});
I have a requirement to provide a button on a grouped row , when onclick of that button , I should capture rowData. I've tried to implement this with custom formatter , grid.SetCell option, but didn't work.
Here is Sample code:
grid.jqGrid({
datatype: 'local',
colNames: ['Id', 'Order Id', 'Name', 'OrderName'],
colModel : [
{ name: 'ID', index: 'ID', editable: true}, //// I grouped by this column
{ name: 'OrderID', index: 'OrderID', width: 30, align: 'center'},
{ name: 'Name', index: 'Name', width: 30, align: 'center'},
{ name: 'OrderName', index: 'OrderName', width: 30, align: 'center'}
],
groupingView: {
groupField: ['ID'],
groupCollapse: true,
groupColumnShow: [false],
groupText: ['<b>{0}</b></div><input type = "button" class = "button" value = "NEW" id = "btnNew" style = "width:100px; hieght:10px" onclick = "javascript:AddNew({OrderID})" /><<b>{1} Orders</b>']
function AddNew(orderId)
{
//// DO SOME THING
}
In above example my grid will be grouped by Id , on each grouped row I need to create a button which onclick event should consist of Order Id. (Order Id is same for all the rows under each group). I need to show Count here also.
I was not able to pass order Id in group Text above, then I use custom formatter on ID column like this .
var html ;
formatter: function(cellValue, options, rowObject)
{
if ((options.rowId.toString()).indexOf("listghead") === -1) {
html = cellvalue + "<input type = "button", value = "New" onclick = AddNew(' +rowObject[1] +')
}
return html;
}
rowObject value has been passed but grouping was broken. If I don't use the above if condition grouping works fine, but onclick event is breaking.
Help me .
Thanks in Advance.
You can get the row value through rowObject so:
html = rowObject.childNodes[1].childNodes[0].wholeText;
This code return a string with the content of rowObject to that columm
You can just pass the rowObject when it comes to group header , and it is not undefined or null when it comes to groupheader.
Just test it using alert(rowObject) when you detect it's group header.
My server provides the following json string:
{
"total":3,
"page":1,
"records":52,
"rows":[
{"cell":[
"6789",
"Veridien Dynamics",
"ver01",
"Description of Site: ver01",
"1986a594-bb12-4a4a-a70b-4b85251fd268",
"UKSODMBHANU01",
6440],
"id":120}
......
]
}
In my grid, I would like to have a link for each row. The link is built using custom formatter. The url for the link needs to include the id (e.g. 120). I cannot obtain the value of id from cellvalue, options, nor the rowObject in my custom formatter. Since id is not part of the 'cell', I don't know how to obtain this value to construct the url.
Following is part of my grid definition :
$("#list").jqGrid({
url:'http://mydomain:8080/myserver/api/v1/data-grid.json',
loadBeforeSend: function(xhr) {
xhr.setRequestHeader("Authorization",'Basic xxxxxxxxxxxxxxxxxxxxxxxxx');
return xhr;
},
datatype: "json",
jsonReader : {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: true,
cell: "cell",
id: "id"
},
colNames:['Customer ID','Customer','Site ID','Site', 'Server ID','Server Name',
'XML Size','id'],
colModel :[
{name:'customerID',editable:false},
{name:'customerName',editable:false},
{name:'siteID',editable:false,width:60, align:'center'},
{name:'siteDescription',editable:false,align:'center'},
{name:'serverID',editable:false,width:150,align:'right'},
{name:'serverName',editable:false, width:150,align:'right'},
{name:'xmlSize',editable:false, align:'right'},
{name:'id', index:'id', editable:false,
align:'center',formatter:that.xmlLinkFormatter},
],
......
}
Following is my xmlLinkFormatter, everything works fine if I hard code the id value here to be part of the targetURL.
xmlLinkFormatter:function(cellvalue, options, rowObject){
var targetURL = "http://mydomain:8080/myServer/data/showXml/"+
IwantIDValue here;
var link = "<a href='javascript: void(0)' onclick=\"window.open('" +
targetURL + "');\">View XML</a>";
return link;
}
I suggest you to use unobtrusive JavaScript to build the link. So the custom formatter can be very easy:
xmlLinkFormatter:function(cellvalue, options, rowObject){
return "<a href='#'>View XML</a>";
}
now the contain of the 'id' column will be the same as in your example. To make 'onclick' binding I suggest to use jQuery.click.
The way how one can implement unobtrusive JavaScript in jqGrid I described here and here. So I will use almost the same way and will use the same simple helper function getColumnIndexByName:
loadComplete: function() {
var i=getColumnIndexByName(myGrid,'id');
// nth-child need 1-based index so we use (i+1) below
$("tbody > tr.jqgrow > td:nth-child("+(i+1)+") > a",myGrid[0]).click(function(e){
var tr=$(e.target,myGrid[0].rows).closest("tr.jqgrow");
//alert("clicked the row with the id='"+tr[0].id+"'");
e.preventDefault();
window.open("http://mydomain:8080/myServer/data/showXml/"+
encodeURIComponent(tr[0].id));
});
}
(the variable myGrid here is defined as var myGrid=$("#list");)
How you can verify in the live demo here, the approach works.