I have a JQGrid with 3 columns. The third column, I want it as a dropdownlist based on some value in the second column. Is this Possible?
Also in the JQGrid demo, do add a dropdown we need to set the edittype to "select" and pass the values in JSON.
edittype:"select",editoptions:{value:"FE:FedEx;IN:InTime;TN:TNT;AR:ARAMEX"}},
My next question is how to pass values to this column from a model object in the format it is expecting.
You can use dataUrl or postData property of editoption defined as function. See the answer or here and here. If you need to send standard URL parameters like /mySetectUrl?status=StatusValue then you can use
name: "Field5", edittype: "select",
editoptions: {
// it produces URL like /mySetectUrl?status=StatusValue
dataUrl: "/mySetectUrl",
postData: function (rowid, value, name) {
return { status: $(this).jqGrid("getCell", rowid, "Status") };
}
}
If you need to construct some another URL like /mySetectUrl/StatusValue you can use dataUrl defined as function:
name: "Field5", edittype: "select",
editoptions: {
// it produces URL like /mySetectUrl/StatusValue
dataUrl: function (rowid, value, name) {
return "/mySetectUrl/" +
encodeURIComponent($(this).jqGrid("getCell", rowid, "Status"));
}
}
Related
sorry for the bad title I cannot express the proper subject to my problem
since, I'm a newbie in MVC and ajax I have a problem
In view I prepared a dropdown where it list all the shoes name (Shoe Table), now the customer has to select it but the twist it must display the Shoesprice (Shoe Table) once it select a shoe name. the view code is given below
View:
#Html.DropDownListFor(x => x.shoename, new SelectList(Model.ShoesModel,"shoename","shoename"), "Select Shoes Name", new {id="myDrop",#class="form-control" })
I have the script when you select it the item, this particular syntax is working
Script:
$("#myDrop").change(function ()
{
var value = $(this).val();
console.log(value);
$.ajax({
type: 'POST',
url: '/Customers/GetShoesPrice',
dataType: 'json',
data: { shoesName: $(this).val() },
success: function (data) {
//how can I declare a value to get the and return the price
}
});
}
But, i don't know how to create an ajax syntax (get the price according to shoe name), and set to a controller
thank you for help
Since you want to return single value only, just use data in AJAX success result to show returned price value:
Controller
[HttpPost]
public JsonResult GetShoesPrice(string shoesName)
{
var customerViewPrice = (from c in _SBC.Shoeses // Change the condition here
where c.shoename.Contains(shoesName)
select c.ShoesUnitPrice).FirstOrDefault(); // or SingleOrDefault() for one and only returned value
return Json(customerViewPrice);
}
View (jQuery)
$("#myDrop").change(function () {
var value = $(this).val();
console.log(value);
$.ajax({
type: 'POST',
url: '/Customers/GetShoesPrice',
dataType: 'json',
data: { shoesName: value },
success: function (data) {
// set input element value which will be posted on form submit with DropDownListFor
$('#price').val(data);
}
});
}
Note that if you want to show list of ShoesUnitPrice from selected shoesName, you need to use $.each() loop to iterate returned array of price value.
I have two select2 dropdowns and I want to change options the second dropdown depending on first dropdown.
For example,
{
data: 'country_id',
editor: 'select2',
renderer: customDropdownRenderer,
select2Options: {
data: {!! $production_units !!} ,
dropdownAutoWidth: true,
}
},
{
data: 'state_id',
editor: 'select2',
renderer: customDropdownRenderer,
select2Options: {
data: [],
dropdownAutoWidth: true,
width: 'resolve'
}
},
Depending on country_id, I want to change select2 options of state_id. I know how to make this work with just select2, but I am not able to figure out how to make it work with handsontable.
I have change select2Options in afterChange, but how to do that?
afterChange: function (change, source) {
if(change)
{
if(change[0][1] == 'country_id')
{
$.get("/api/states?country="+change[0][3], function(data){
//What should be done here?
});
}
}
},
You retrieve all the states for that country. Make sure the states list is in the same format that select2 expects.
Then loop through the columns list and determine the dependent column for the current column that has been modified.
Get the cell properties:
var cellProperties = instance.getCellMeta(rowIndex, dependentColumnIndex);
Update the select2 source:
cellProperties['select2Options'].data = [states list];
I have two views in database. Bonuses and employees. One(employee)-to-many(bonuses).
I have kendo ui grid (kendo web), which displays ajax results from controller called Bonuses
And an autocompliting element - Employee Combobox binded with Employee filed of a grid.
Grid's datasource:
// bind json result from /Bonuses/GetPagedJsonBonuses
var bonusesDataSource = new kendo.data.DataSource({
transport: {
read: "#Url.Action("GetPagedJsonBonuses", "Bonuses")",
update: {
url: "#Url.Action("Edit", "Bonuses")",
type: "PUT"
},
create: {
url: "#Url.Action("Create", "Bonuses")",
type: "POST"
},
parameterMap: function(options, operation) {
if (operation === "update" || operation === "create") {
// updates the BonusDTO.EmployeeId with selected value
if (newValueEmployeeId !== undefined)
options.EmployeeId = newValueEmployeeId;
}
return options;
}
},
schema: {
data: "Data", // PagedResponse.Data
total: "TotalCount", // PagedResponse.TotalCount
model: {
id: "BonusId", // Data
fields: {
EmployeeId: { type: "number" },
EmployeeLastName: {
type: "string",
editable: true,
//validation: { required: {message: "Employee's last name is required"}}
},
Amount: {
type: "number",
editable: true,
nullable: false,
validation: {
required: { message: "Amount is required to be set" }
}
}
} // fields
} // model
}// schema
});
Grid element looks like this:
// creates bonuses grid control
$("#bonusesGrid").kendoGrid({
dataSource: bonusesDataSource,
toolbar: ["create"],
editable: "inline",
columns: [
"BonusId",
"EmployeeId",
{
field: "EmployeeLastName",
editor: employeeAutocompletingEditor,
template: "#=EmployeeLastName#"
},
"Amount",
{
command: ["edit"],
title: " "
}
],
save: function(e) {
if (newValueEmployeeId !== undefined && newValueEmployeeLastName !== undefined) {
e.model.EmployeeId = newValueEmployeeId; // it's a hack to bind model and autocomplete control
e.model.EmployeeLastName = newValueEmployeeLastName;
}
},
edit: function(e) {
setCurrentValueEmployeeIdAndLastName(e.model.EmployeeId, e.model.EmployeeLastName);
},
cancel: function(e) {
setCurrentValueEmployeeIdAndLastName(e.model.EmployeeId, e.model.EmployeeLastName);
}
});
Autocompleting combobox has it's own datasource using ajax:
// datasource for autocomlete combobox to lookup employees names from
var employeesDataSource = new kendo.data.DataSource({
transport: {
read: "#Url.Action("GetJsonEmployeesByLastName", "Bonuses")",
},
parameterMap: function(options, operation) {
if (operation === "update" || operation === "create") {
setNewValueEmployeeIdAndLastName(options.Id, options.LastName);
}
return options;
},
});
Autocompliting combobox look's like this:
function employeeAutocompletingEditor(container, options) {
$('<input required data-text-field="LastName" data-value-field="EmployeeId" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoComboBox({
// sets the local variables to update values of current row.
change: function() {
setNewValueEmployeeIdAndLastName(this.value(), this.text());
},
dataBinding: function (e) {
console.log("dataBinding: ", e, this.dataItem());
},
dataBound: function (e) {
console.log("dataBound: ", e, this.dataItem());
},
dataSource: employeesDataSource
});
}
I use Editor binding to pass values(EmployeeId) and Text (EmployeeLastName) from grid to combobox.
I also use a hack like temporal variables (newValueEmployeeId, currentValueEmployeeId) to
send selected Employee in combobox and pass it to grid for correct save. A found it's a most common practice to pass a value back to grid.
My problems is:
If I press Edit button on my grid first time The combobox displays current employee's name from grid row:
If I press Cancel button and again press Edit button, combobox doesn't display current value of grid (employee's name)
IF I type some name, change some other values, and Udate(save) value, next time combobox again displays employees name, but only once before Cancel was pressed.
I'm very new in Kendo UI and this problem drives me crazy...
I think that combobox losts it's binding or doesn't update smth. I tried to set values while onBound and onBinding events, but this doesn't help. Please help me with an advice and example.
PS all evenets and functions is my try to debug and find solution.
only one fix helped me:
var employeeList = new List<Employee>()
employeeList.add(new Emplpyee()) // add fake employee record.
return Json(employeeList)
I don't know why, but grid control start make cyclying empty ajax requests if I return empty list of employees or null. This doesn't work:
return Json(new List<Employee>());
return Json(null);
I think it's a problem in kendo combobox itself ,because it's not ready to receive and handle empty list or null as json result.
Also I heared something, that JQuery doesn't support empty or null results anymore...maybe that's the reason
I have a class (Person) with 4 properties : Id, FirstName, LastName, Code.
I show a person list in a jqgrid. I'd like a link column with this format (the code has this format 2011.0001)
/Person/Detail/Code => /Person/Code/2011.0001
But I have this with the code below :
/Customer/Detail?Code=2
I tried this :
colModel: [
{ name: 'Code', index: 'Code', formatter: 'showlink', formatoptions: { baseLinkUrl: '/Customer/Detail', idName: 'Code' }},
{ name: 'LastName', index: 'LastName', align: 'left' },
{ name: 'FirstName', index: 'FirstName', align: 'left' }
],
How can I correct this ?
Thanks,
Update1, Data format
[
{"Id":1,"FirstName":"AAAA","LastName":"AA","Code":"2011.0001"},
{"Id":3,"FirstName":"BBBB","LastName":"BB","Code":"2011.0003"}
]
You can try to use the custom formatter in the form
formatter: function (cellvalue, options, rowObject) {
return '' + cellvalue + '';
}
instead of predefined formatter 'showlink':
formatter: 'showlink', formatoptions: {baseLinkUrl:'/Customer/Detail', idName:'Code'}
You can easy receive /Customer/Detail?Code=2011.0001 if you have unique data in the 'Code' column and if you would add key: true to the column definition. In the case the Id value from the JSON input will be ignored and the value from the 'Code' column will be used as the rowid. If you do need to have the href value in the form /Customer/Detail/Code/2011.0001 or instead of /Customer/Detail?Code=2011.0001 you will need use custom formatter as I described before.
I'm using jqGrid to display tabular data on my first ASP.NET MVC 3 and find it really useful, particularly filtering down data. For string-type I use the column-filtering with "contains" and that works wonderfully for culling out the strings. For the date data I use the date picker. Great.
Now I've got a few columns (e.g., "Contains nuts") which are essentially boolean values. I want to provide a way to filter these. Right now they are displayed as "true" and "false" and use the same string-based filtering that my string-type columns use. That's a bit clunky. I think what I'd like to do instead is have a way to choose one of three values (true/false/both) via a dropdown mechanism.
My current colModel has an entry like so for my 'boolean' field:
{ name: 'ContainsNuts',
index: 'ContainsNuts',
align: 'left',
searchoptions: { sopt: ['eq, 'ne']}
}
which only works when the user types in 'false' or 'true' - again, clunky.
For a few other columns, I wanted to use dropdowns for enumerations, e.g., I have a 'Cones' column, since there are quite a few rows and I page the results - using the auto complete text filtering is a bit hit-or-miss for the user to find all the possible values. Hope that makes sense.
So what I've tried is this - I created a controller action that looks like so:
public JsonResult AvailableCones()
{
var context = new IceCreamEntities();
var query = context.Cones.AsQueryable().Distinct();
List<string> all = query.Select(m => m.Name).ToList();
return Json(all, JsonRequestBehavior.AllowGet);
}
And I did something like this [perhaps convoluted approach] to create a dropdown selection in the filtering dialog for Cones in my document ready:
...
createSearchSelection = function (someValues) {
var outputValues = "";
if (someValues && someValues.length) {
for (var i = 0, j = someValues.length; i < j; ++i) {
var entry = someValues[i];
if (outputValues.length > 0) {
outputValues += ";";
}
outputValues += entry + ":" + entry;
}
}
return outputValues;
}
setTheSearchSelections = function (colName, url){
$('#icecreamgrid').jqGrid('setColProp', colName,
{
stype: 'select',
searchoptions: {
value: createSearchSelection(url),
sopt: ['eq']
}
});
}
gotData = function(data) {
setTheSearchSelections('ConeType', data);
}
var url = "/IceCream/AvailableConeTypes";
$.get(url, null, gotData);
The result is that I get a drop-down for the ConeType column in the search dialog and the correct rows shows up in the column. Great. That's pretty cool that it works.
What I don't know how to do, however, is to get a dropdown to show up in my column header filter just like the one that now shows up in the filter dialog. How can I augment what I have to make this happen? Secondly, how can I make what I've got work for boolean values?
First part of your question is the displaying and filtering of the boolean values. I use checkboxes to display such values. In difference on your case I have typically many such columns. To reduce the size of the JSON data I use "1" and "0" instead of "true" and "false". Next I use the following column settings
formatter: 'checkbox', align: 'center', width: 20,
edittype: 'checkbox', editoptions: { value: "1:0" },
stype: "select", searchoptions: { sopt: ['eq', 'ne'], value: "1:Yes;0:No"
So for the searching the user have to choose "Yes" or "No" in the select box. Because I have many of such columns I defined templateCeckbox object in one JavaScript file which I include on every page of the project:
my.templateCeckbox = {
formatter: 'checkbox', align: 'center', width: 20,
edittype: 'checkbox', editoptions: { value: "1:0" },
stype: "select", searchoptions: { sopt: ['eq', 'ne'], value: "1:Ja;0:Nein" }
};
Then the typical column definition is
{
name: 'IsInBasis', index: 'InBasis', template: my.templateCeckbox,
cellattr: function () { return ' title="TS-Basis"'; }
},
(see the answer for details about the column templates). I find also practical if the tooltip shown if one hover the checkbox will be the text close to the column header. So I use cellattr attribute. In case of having many columns with the checkboxes it improves the usability a little.
To be able to display many columns with chechboxes I use personally vertical column headers. I recommend you to read the old answer which could be additionally interesting because it describes how to implement quick filtering of the data with respect of external checkbox panel.
Now about the building of the selects for the 'Cones' column. If you has AvailableCones action which provide the list of possible options like array (list) of strings you should use dataUrl:'/IceCream/AvailableConeTypes' instead of value: createSearchSelection(url) as the searchoptions. You well add only the buildSelect function which I described in "UPDATED" part of the answer.
{
name: 'ConeType', width: 117, index: 'ConeType', editable: true, align: 'center',
edittype: 'select', stype: 'select',
editoptions: {
dataUrl: urlBase + '/AvailableConeTypes',
buildSelect: my.buildSelect
},
searchoptions: {
dataUrl: urlBase + '/AvailableConeTypes',
buildSelect: my.buildSelect
}
}
where
my.buildSelect = function(data) {
var response = jQuery.parseJSON(data.responseText),
s = '<select>', i, l, ri;
if (response && response.length) {
for (i=0, l=response.length; i<l; i += 1) {
ri = response[i];
s += '<option value="' + ri + '">' + ri + '</option>';
}
}
return s + '</select>';
};
This line of code shows a True,False dropdownlist for a column that has true, false values:
{
name: 'SReqdFlag', index: 'SReqdFlag', editable: true, edittype: 'select', editoptions: { value: '"":Select;true:True;false:False' }
}
Hope that helps!