Telerik Forums
Kendo UI for jQuery Forum
4 answers
1.5K+ views
Hi,

I've been trying to get this to work for several days now and it just won't work. I'm not sure what the process is for getting help, but I would like to submit a support ticket so I can get this resolved quickly.

The problem:
Once I add a custom editor to the grid it creates duplicate records on create, records are not updated when edited even though the grid display shows the edits and the destroy/delete does not work, no records are deleted even though the grid removes the row from the grid. Also, I could not get the combobox to work using a remote data source (json/php) I had to hard code the list in order for it to work, even though my json is working in the browser.

I'm including the code here, but would like to submit the ticket so that I can not only get this fixed but I also want to understand why this doesn't work when it seems like it should. You'll notice that the php is almost directly taken from the 2 tutorials on the blog. However, and I'll use this to rant a bit, there are no examples in php for deleting a record. Please try and include complete crud examples!

Thanks for looking and please contact me about scheduling a ticket.

Tony

Data-source declaration:

var expense = new kendo.data.DataSource({
            transport: {
        read: {
        url: "../data/expenses.php?StatementID=<?php echo $_SESSION['StatementID']; ?>",
        dataType: "json",
        type: "GET"
        },
        create: {
             url: "../data/expenses-add.php?StatementID=<?php echo $_SESSION['StatementID']; ?>",
             dataType: "json",
        type: "PUT"
              },
        update: {
            url: "../data/expenses-update.php",
        dataType: "json",
        type: "POST"    
              },
          destroy: {
          url: "../data/expenses-delete.php",
         dataType: "json",
         type: "DELETE"                            
  }
    },
    pageSize: 50,
    autoSync: false,
    schema: {
        data: "data",
                                    model: {
                                           id: "ID",
                                        fields: {
        ID: {editable: false } ,
                                    StatementID: { editable: false},
                                    ExpenseType: "Type",
        ExpenseAmount: {editable: true, type: "number" },
        Notes: {editable: true, type: "string" }
                                    }
                                }
                            }
                        });
 
Tried this to feed the combobox but couldn't get it to work:

 /* var typeDataSource = new kendo.data.DataSource({
                       transport: {
                        read: "../data/expense-types.php"
    }
                }); */

datasource for combobox(works fine, but I need this to work with the above)
   var types = [ {
                 "ID": 1,
                  "Expense": "Airfare"
                }, {
    "ID": 2,
                 "Expense": "Ground Trasportation"
                }, {
    "ID": 2,
                 "Expense": "FedEx"
                }, {
    "ID": 2,
                  "Expense": "Side-man Pay"
                }, {
    "ID": 2,
                 "Expense": "Hotel"
                }, {
    "ID": 2,
                  "Expense": "Conference Fee-Charge"
                }, {
    "ID": 2,
                  "Expense": "Advance"
      }];


  Grid declaration:              
 
                    $("#expenses").kendoGrid({
                          dataSource: expense,
                          pageable: true,
        sortable: true,
        autoBind: true,
        height: 400,
        toolbar: ["create"],
                           columns: [                            
                               { field: "ExpenseType", title:"Type", width: "150px", editor: function (container, options) {
                    $('<input data-text-field="Expense" data-value-field="Expense" data-bind="value:' + options.field + '"/>')
                        .appendTo(container)
                        .kendoComboBox({
                            autoBind: false,
                            dataSource: types
                        });
                      }
    },
    { field: "ExpenseAmount", title:"Amount", width: "75px", format: "{0:c}" },
    { field: "Notes", title:"Note", width: "200px" },
    { command: ["edit", "destroy"], title: "&nbsp;", width: "150px" }
                            ],
    editable: "popup"
                    });

PHP to handle the Update (POST):
                    
<?php
$link = mysql_pconnect("localhost", "user", "pass") or die("Unable To Connect To Database Server");
mysql_select_db("db") or die("Unable To Connect To DB");

// add the header line to specify that the content type is JSON
header("Content-type: application/json");

// determine the request type
$verb = $_SERVER["REQUEST_METHOD"];
    // handle a POST
if ($verb == "POST") {

// get the parameters from the post. escape them to protect against sql injection.
$Id = mysql_real_escape_string($_POST["ID"]);
$ExpenseType = mysql_real_escape_string($_POST["ExpenseType"]);
$ExpenseAmount = mysql_real_escape_string($_POST["ExpenseAmount"]);
$Notes = mysql_real_escape_string($_POST["Notes"]);
    
$rs = mysql_query("UPDATE Expenses SET `ExpenseType` = '".$ExpenseType."', `ExpenseAmount` = '".$ExpenseAmount."', `Notes` = '".$Notes."' WHERE `ID` = '".$ID."'");
   
 if ($rs) {
    
   echo "" .$Id. "";
 }
else {
     header("HTTP/1.1 500 Internal Server Error");
      echo "Update failed for ID: " .$Id;
    }
}
?>

PHP to handle the Create (PUT):
<?php
$link = mysql_pconnect("localhost", "user", "pass") or die("Unable To Connect To Database Server");
mysql_select_db("db") or die("Unable To Connect To DB");

// add the header line to specify that the content type is JSON
header("Content-type: application/json");

// determine the request type
$verb = $_SERVER["REQUEST_METHOD"];

 // handle a Put
if ($verb == "PUT") {
$request_vars = Array();
parse_str(file_get_contents('php://input'), $request_vars );
//get the parameters from the post. escape them to protect against sql injection.
$ExpenseType = mysql_real_escape_string($request_vars["ExpenseType"]);
$ExpenseAmount = mysql_real_escape_string($request_vars["ExpenseAmount"]);
$Notes = mysql_real_escape_string($request_vars["Notes"]);
 $StatementID = mysql_real_escape_string($_GET["StatementID"]);   
   $sql = "INSERT INTO Expenses (`StatementID`, `ExpenseType`, `ExpenseAmount`, `Notes`) VALUES ('".$StatementID."', '".$ExpenseType."', '".$ExpenseAmount."', '".$Notes."')";
   
  $rs = mysql_query($sql);

    if ($rs) {
$ID = mysql_insert_id();
        echo $ID;
    }
    else {
        header("HTTP/1.1 500 Internal Server Error");
        echo false;
    }
}
?>

PHP to handle Destroy(DELETE):

<?php
$link = mysql_pconnect("localhost", "user", "pass") or die("Unable To Connect To Database Server");
mysql_select_db("db") or die("Unable To Connect To DB");
// add the header line to specify that the content type is JSON
header("Content-type: application/json");

// determine the request type
$verb = $_SERVER["REQUEST_METHOD"];
if ($verb == "DELETE") {
 
// get the parameters from the post. escape them to protect against sql injection.
$ID = mysql_real_escape_string($_GET["ID"]);
    
   $sql= "DELETE FROM Expenses WHERE ID = '".$ID."'";
   
  $rs = mysql_query($sql);

    if ($rs) {
        echo "".$ID."";
    }
    else {
       header("HTTP/1.1 500 Internal Server Error");
        echo false;
    }
}
?>
Fernando
Top achievements
Rank 1
 answered on 11 Jul 2012
6 answers
407 views
My general goal is this: I have two views, each with a <Select> control.  After the user selects a value in the first <select> control, I wish to fill the second <select> based on the first value.  

For example, the 1st select allows the user to choose a customer, then the 2nd select in the 2nd view is filled with locations where that customer operates. (and only that customer).

This seems like a common thing people would need to do, so I bet there's a simple solution that I'm missing, being pretty new to web development in general.  My apologies if this is the case.

My first attempt was to add an "onchange=method" property to the 1st select, and point it to a method to fill the 2nd select.  This did nothing, the method was not invoked.  I determined that I needed to set AutoPostBack="True".  I did this by replacing the <select> with <asp:DropDownList > since the <select> did not appear to support the autopostback property.

This failed to work at all on Opera running under the Android 2.3.3 emulator.
This *kinda* worked worked when viewed on Chrome under Windows, the method is invoked, but then after the postback, the entire app is reloaded and it goes back to a view before the one with the 1st select.  And even if it went to the correct view, this reloading of the app would be pretty bad anyway. And regardless, it's a mobile app that has to work on mobile browsers.

Is there a different approach to accomplish this?  Do I have use AJAX?  

FYI, I am developing in Visual Studio 2010, and using C# for the code behind.

Thanks,
Tim

Greg
Top achievements
Rank 1
 answered on 11 Jul 2012
1 answer
128 views
in your example online when I add a record and fill out the field "Units in stock," there is an error in the compilation:
Example, entering 7.5, video displays 7.05, I will illustrate the sequence::
The field has the default value 0| ( | cursor position)
I hit 7 in numeric keyboard
appears on the screen 7|0
I press "." in numeric keyboard
appears on screen 7.0|
I press 5 on the numeric keyboard
Video appears to 7:05|

Tips ... ?
Thank you.
Mike
Top achievements
Rank 1
 answered on 11 Jul 2012
0 answers
204 views
I'm considering using KendoUI for a mobile app and I was wondering if it supports oauth 1.0 as part of the DataSource component or in some other way? More specifically can I do a full oauth handshake to get an access token and then can I make ajax calls using that token (along with the other parameters required by the protocol)

Thanks, r.
Russell
Top achievements
Rank 1
 asked on 11 Jul 2012
2 answers
222 views
I have a remote json datasource which comes in as follows:

[["Advantage", null, "2012-05-07T01:54:02.130000", "sqlsvrautosysjobs", "2012-05-07T01:54:02.130000", "sqlsvrautosysjobs", 1], ["ALDOP", null, "2012-05-07T01:54:02.130000", "sqlsvrautosysjobs", "2012-05-07T01:54:02.130000", "sqlsvrautosysjobs", 1]]

How can I bind my datasource to this?  I cannot change the datasource so I will need to use ordinal references or something like that.  I've tried the following with no luck:

$("#grid").kendoGrid({
    dataSource: {
        type: "json",
        transport: {
            read: {
                url: 'list',
                dataType: 'json',
                contentType: 'application/json'
            }
        },
        schema: {
            model: {
                fields: {
                    SourceSystem: { type: "string" },
                    ModifiedComment: { type: "string" },
                    CreatedDate: { type: "date" },
                    ModifiedDate: { type: "date" },
                    ModifiedUser: { type: "string" },
                    Version: { type: "number" }
                }
            }
        },
        pageSize: 10,
        serverPaging: true,
        serverFiltering: true,
        serverSorting: true
    },
    height: 250,
    filterable: true,
    sortable: true,
    pageable: true,
    columns: [{
            field:"SourceSystem",
            title: "Source"
        }, {
            field: "ModifiedComment",
            title: "Comment",
            filterable: false
        },
        "Version",
        {
            field: "CreatedDate",
            title: "Created Date",
            width: 100,
            format: "{0:MM/dd/yyyy}"
        }, {
            field: "ModifiedDate",
            title: "Modified Date",
            width: 100,
            format: "{0:MM/dd/yyyy}"
        }, {
            field: "ModifiedUser",
            title: "Modified By"
        }
    ]
});

Any ideas?
Darren
Top achievements
Rank 1
 answered on 11 Jul 2012
2 answers
143 views
I've downloaded in the 2012 Q2 beta and the "changes" file under treeview says only:
  • Allow disabled items to be expanded / collapsed through the API
In December 2011, there was discussion of dynamic loading capability being added to the Jan 2012 release.
It didn't happen.
I also saw discussion of dynamic loading of tree data being added to the march 2012 release. 
It didn't happen.
Based on the beta doc above, It appears that dynamic loading for treeview won't happen for the 2012 Q2  (July) release.
Is this correct?
I've asked about this feature before but have not had a response.
Here's what I think would be enough for my application:
Display the expansion triangle regardless of whether a node has children or not.
Then there would be something for a user to click on and I could handle the event and 
get the children from the server and populate the tree with custom javascript.
The "don't display expansion triangle if no children" is "too clever". Please add 
a configuration option to a tree to "disable" this "too clever" feature.

If no response to this message (just like my other questions), I'll assume Treeview is no longer being worked on.
Christopher
Top achievements
Rank 1
 answered on 11 Jul 2012
0 answers
153 views
I have a gridview that allows users to upload a picture, but want to allow them the ability move the records up or down in within the gridview.  I have written some code, and everything in the row moves, expect for the image.  Can anyone tell me where I am going wrong?

View: 
@using ACS.CSG.ReviewContentManager.Models
@model ACS.CSG.ReviewContentManager.Models.AttributeViewModel 

@{
var lockTitle = Model.IsLocked ? "Locked" : "Unlocked";
var lockImage = Url.Content(String.Format("~/Content/Common/Images/Icons/{0}.png", Model.IsLocked ? "locked" : "unlocked"));

}
@using (Html.BeginForm())
{
<fieldset>
<legend>Attribute</legend>

@Html.HiddenFor(model => model.ID)
<table class="t-separator" width="100%">
<tr>
<td align="right">
@Html.LabelFor(m => m.LongName, new { @class = "editor-label required" }):
</td>
<td>
@Html.TextBoxFor(m => m.LongName, new { @class = "display-field" })
@Html.ValidationMessageFor(m => m.LongName)
</td>
<td align="right">
@Html.LabelFor(m => m.ShortName, new { @class = "editor-field" }):
</td>
<td>
@Html.TextBoxFor(m => m.ShortName, new { @class = "display-field" })
@Html.ValidationMessageFor(m => m.ShortName)
</td>
<td style="vertical-align:middle;" align="right">
@Html.LabelFor(model => model.Class, new { @class = "editor-label" }):&nbsp;
</td>
<td style="vertical-align:middle;">
@Html.EditorFor(model => model.ClassValue, "Class", new { @class = "editor-field" })
@Html.ValidationMessageFor(model => model.Class)
</td>
</tr>
<br />
<tr>
<td style="vertical-align:middle;" align="right">
@Html.LabelFor(m => m.AnswerType, new { @class = "editor-label required" }):
</td>
<td colspan="6" style="vertical-align:middle;">&nbsp;
@Html.EditorFor(m => m.AnswerTypeValue, "AnswerType", new { @class = "editor-field", style = "width: 210px;" })
@Html.ValidationMessageFor(m => m.AnswerType)
</td>
<td rowspan="3">
<button id="lock" title="@lockTitle" class="entity-action"><img alt="@lockTitle" height="24" src="@lockImage" width="24" /></button>
<button id="save" title="Save" class="entity-action"><img alt="Save" height="24" src="@Url.Content("~/Content/Common/Images/Icons/save.png")" width="24" /></button>
<button id="cancel" title="Exit" class="entity-action"><img alt="Exit" height="24" src="@Url.Content("~/Content/Common/Images/Icons/cancel.png")" width="24" /></button>
</td>
</tr>
<br />
<tr>
<td align="right">
@Html.LabelFor(m => m.Information):
</td>
<td colspan="6">
@Html.TextAreaFor(m => m.Information, new { @class = "wide-text", style = "width: 86%;" })
@Html.ValidationMessageFor(m => m.Information)
</td>
</tr>
</table>

<hr />


@(Html.Telerik().Splitter().Name("AnswerOptionSplitter")
.Orientation(SplitterOrientation.Horizontal)
.Panes(panes =>
{
panes.Add()
.Size("28px")
.Resizable(false)
.Content(@<text>
<div class="entity-tools-vertical">
<button id="editAnswerOption" title="Edit" class="entity-action"><img alt="Edit" height="24" src="@Url.Content("~/Content/Common/Images/Icons/edit-disabled.png")" width="24" /></button>
<button id="moveUpAnswerOption" title="Move Up" class="entity-action"><img alt="Move Up" height="24" src="@Url.Content("~/Content/Common/Images/Icons/up-disabled.png")" width="24" /></button>
<button id="moveDownAnswerOption" title="Move Down" class="entity-action"><img alt="Move Down" height="24" src="@Url.Content("~/Content/Common/Images/Icons/down-disabled.png")" width="24" /></button>
<button id="toggleEnableAnswerOption" title="Enabled" class="entity-action"><img alt="Enabled" height="24" src="@Url.Content("~/Content/Common/Images/Icons/accept-disabled.png")" width="24" /></button>
<button id="deleteAnswerOption" title="Delete" class="entity-action"><img alt="Delete" height="24" src="@Url.Content("~/Content/Common/Images/Icons/recycle-disabled.png")" width="24" /></button>
</div>
</text>);
panes.Add()
.Resizable(false)
.Content(
@Html.Telerik().Grid<AnswerOptionViewModel>()
.Name("AnswerOptions")
.ToolBar(command => command.Insert().ButtonType(GridButtonType.ImageAndText))
.DataKeys(k => k.Add(o => o.ID))
.DataBinding(dataBinding => dataBinding.Ajax()
.OperationMode(GridOperationMode.Client)
.Select("_AnswerOptionsAjax", "Attribute", new { id = Model.ID })
.Update("_AnswerOptionsUpdateAjax", "Attribute", new { attributeId = Model.ID })
.Delete("_AnswerOptionsDeleteAjax", "Attribute", new { id = Model.ID })
.Insert("_AnswerOptionsCreateAjax", "Attribute", new { id = Model.ID})
)
.Columns(columns =>
{
columns.Bound(m => m.AnswerAbbr).Title("");
columns.Bound(m => m.AnswerText).Title("");
columns.Bound(m => m.AnswerValue).Title("").Width(32);
columns.Bound(m => m.RelatedImageId).Title("");
columns.Bound(m => m.RelatedImage).Title("")
.ClientTemplate("<img alt='<#= AnswerText #>' class='answer-option-icon' src='"
+ Url.Action("AttributeAnswerOption", "ImageGenerator", new { id = Model.ID, index = 0, })
+ "' />").Width(32);
columns.Bound(m => m.Ordinal).Hidden().HtmlAttributes(new { style = "display: none;" });
})
.ClientEvents(c => c
.OnRowSelect("AnswerOptions_onRowSelect")
.OnDataBound("AnswerOptions_onDataBound")
.OnSave("AnswerOptions_onGridSave")
)
.HtmlAttributes(new { @class = "t-widget t-grid grid-no-header grid-no-footer" })
.Selectable()
.Editable(e => e.Mode(GridEditMode.PopUp))
.ToHtmlString()
);
})
)

</fieldset>
<style type="text/css">
.t-edit-form-container
{
width: 500px;
margin: 1px;
}
</style>

}
<script type="text/javascript">
//<![CDATA[
// Shared Functions

function enableImage($img) {
var src = $img.attr('src');
var re = /(.+)\-disabled(\.png)/i;
if (re.test(src))
src = src.replace(re, '$1$2');

$img.attr('src', src);
}

function disableImage($img) {
var src = $img.attr('src');
if (src.contains('-disabled') === false)
src = src.replace(/(.+)(\.png)/i, '$1-disabled$2');

$img.attr('src', src);
}

function enableButton($btn) {
if ($btn.is(':disabled'))
$btn.removeAttr('disabled');

enableImage($btn.find('img:first'));
}

function disableButton($btn) {
if ($btn.not(':disabled'))
$btn.attr('disabled', 'disabled');

disableImage($btn.find('img:first'));
}

// Set Common Variables

var gridAnswerOptions = null,
$selectedRow = null,
selectedRowIndex = -1,
isDirty = false,
changedFields = [],
isNew = @((Model.ID == Guid.Empty).ToString().ToLower()),
isNewAnswerOption = false,
lockTitle = '@(lockTitle)',
lockImage = '@(lockImage)'
;

var attribute = @Html.Raw(Json.Encode(Model));

// Page Load Events

jQuery(function () {
gridAnswerOptions = jQuery('#AnswerOptions').data('tGrid');

disableButton(jQuery('#save'));
// set onchange for form inputs to handle dirty state
// rudimentary implementation only sets the flag if any change--even undo--occurs
jQuery('.editor-field').each(function () {
var $ele = jQuery(this);
$ele.change(function (e) {
isDirty = true;
if (jQuery.inArray($ele.text(), changedFields) == -1)
changedFields.push($ele.text());

enableButton(jQuery('#save'));
});
});

jQuery('#Class').bind('valueChange', function () {
isDirty = true;
if (jQuery.inArray('Class', changedFields) == -1)
changedFields.push('Class');

enableButton(jQuery('#save'));
});

// bind and trigger AnswerType_onChange which sets current display of AnswerOptions
jQuery('#AnswerType').bind('valueChange', AnswerType_onChange).trigger('valueChange');

if (isNew)
disableButton(jQuery('#lock'));
else
enableButton(jQuery('#lock'));


// AJAXify attribute buttons
jQuery('#lock').click(function (e) {
if (e.preventDefault) e.preventDefault();
isDirty = true;
if (jQuery.inArray('State', changedFields) == -1)
changedFields.push('State');

var url = '@Url.Action("_LockAjax", new { id = Model.ID })';
jQuery.post(url, jQuery('form').first().serialize(), function (data) {
gridAnswerOptions.refresh();
});

return false;
});

jQuery('#save').click(function (e) {
if (e.preventDefault) e.preventDefault();

// cause client-side validation
var $form = jQuery('form');
if ($form.valid()) {
var url = '@Url.Action("_SaveAjax", new { id = Model.ID })';
jQuery.post(url, jQuery('form').first().serialize(), function (data) {
isDirty = false;
gridAnswerOptions.refresh();
});
}

return false;
});


var exitDialog;
jQuery('#cancel').click(function (e) {
if (e.preventDefault) e.preventDefault();

var $form = jQuery('form');
var redirectUrl = '@Url.Action("Index", "Attribute")';
// prompt to save changes if there are any
if (isDirty && $form.valid()) {
if (!exitDialog) {
// create and display the dialog
exitDialog = jQuery.telerik.window.create({
title: 'Exit Edit Attribute',
modal: true,
resizable: false,
draggable: false,
visible: false,
html: 'The following fields have changed: '
+ changedFields.join(', ')
+ '<br /><br />Do you want to save your changes?'
+ '<button class="exit-dialog-button-yes" title="Yes">Yes</button>'
+ '<button class="exit-dialog-button-no" title="No">No</button>'
})
.data('tWindow');
}

exitDialog.center().open();
jQuery(exitDialog.element).find('.exit-dialog-button-yes').first().click(function (e) {
if (e.preventDefault) e.preventDefault();

var url = '@Url.Action("_SaveAjax", new { id = Model.ID })';
jQuery.post(url, jQuery('form').first().serialize(), function (data) {
exitDialog.close();
window.location = redirectUrl;
});

return false;
});
jQuery(exitDialog.element).find('.exit-dialog-button-no').first().click(function (e) {
if (e.preventDefault) e.preventDefault();

exitDialog.close();
window.location = redirectUrl;

return false;
});
}

return false;
});

// set AnswerOption button state to disabled, where relevant
disableButton(jQuery('#editAnswerOption'));
disableButton(jQuery('#moveUpAnswerOption'));
disableButton(jQuery('#moveDownAnswerOption'));
disableButton(jQuery('#toggleEnableAnswerOption'));
disableButton(jQuery('#deleteAnswerOption'));

// wire up answer option button events

jQuery('#editAnswerOption').click(function (e) {
if (e.preventDefault) e.preventDefault();
isDirty = true;

if (jQuery(this).is(':disabled') || $selectedRow == null)
return false;

gridAnswerOptions.editRow($selectedRow);


// show and set click handlers for update/cancel
$selectedRow.find('.entity-action-update').each(function () {
var $that = jQuery(this);
$that.show();
$that.click(function (e) {
if (e.preventDefault) e.preventDefault();
isDirty = true;

gridAnswerOptions.updateRow($selectedRow);
selectedRowIndex = $selectedRow[0].sectionRowIndex;
gridAnswerOptions.refresh();

return false;
});
});
$selectedRow.find('.entity-action-cancel').each(function () {
var $that = jQuery(this);
$that.show();
$that.click(function (e) {
if (e.preventDefault) e.preventDefault();
if (gridAnswerOptions.cancel) gridAnswerOptions.cancel();
// hide edit-related update/cancel
jQuery('.entity-action-update, .entity-action-cancel').each(function () {
jQuery(this).hide();
});
return false;
});
});

return false;
});

jQuery('#moveUpAnswerOption').click(function (e) {
if (e.preventDefault) e.preventDefault();
isDirty = true;
debugger;
var rowIndex = $selectedRow[0].sectionRowIndex;
if (rowIndex > 0) {
var url = '@Html.Raw(Url.Action("_AnswerOptionsMoveRow", new { id = Model.ID, index = 0, num = -1 }))'.replaceIndexParam(rowIndex);
jQuery.post(url, function (data) {
selectedRowIndex = data.index;
gridAnswerOptions.refresh();
});
}

return false;
});

jQuery('#moveDownAnswerOption').click(function (e) {
if (e.preventDefault) e.preventDefault();
isDirty = true;
debugger;
var rowIndex = $selectedRow[0].sectionRowIndex;
if (rowIndex < $selectedRow.parent().children().length - 1) {
var url = '@Html.Raw(Url.Action("_AnswerOptionsMoveRow", new { id = Model.ID, index = 0, num = 1 }))'.replaceIndexParam(rowIndex);
jQuery.post(url, function (data) {
selectedRowIndex = data.index;
gridAnswerOptions.refresh();
});
}

return false;
});

jQuery('#toggleEnableAnswerOption').click(function (e) {
if (e.preventDefault) e.preventDefault();
isDirty = true;

var rowIndex = $selectedRow[0].sectionRowIndex;
var url = '@Html.Raw(Url.Action("_AnswerOptionsToggleEnableAjax", new { id = Model.ID, index = 0 }))'.replaceIndexParam(rowIndex);
jQuery.post(url, function (data) {
selectedRowIndex = data.index;
gridAnswerOptions.refresh();
});

return false;
});

jQuery('#deleteAnswerOption').click(function (e) {
if (e.preventDefault) e.preventDefault();
isDirty = true;

var rowIndex = $selectedRow[0].sectionRowIndex;
if (gridAnswerOptions.editing.confirmDelete === false || confirm(gridAnswerOptions.localization.deleteConfirmation)) {
var url = '@Html.Raw(Url.Action("_AnswerOptionsDeleteAjax", new { id = Model.ID, index = 0 }))'.replaceIndexParam(rowIndex);
jQuery.post(url, function (data) {
selectedRowIndex = data.index;
gridAnswerOptions.refresh();
});
}

return false;
});
});

// AnswerType Events

function AnswerType_onChange() {
isDirty = true;
enableButton(jQuery('#save'));
if (jQuery.inArray('AnswerType', changedFields) == -1)
changedFields.push('AnswerType');

// only show AnswerOptions if (Multiple) Specified Options is selected
var answerTypeData = jQuery(this).data('tComboBox');
var answerType = answerTypeData.text();

if (answerType.toLowerCase().contains('specified options'))
jQuery('#AnswerOptionSplitter').show();
else {
jQuery('#AnswerOptionSplitter').hide();

// remove the AnswerOptions collection
var url = '@Html.Raw(Url.Action("_AnswerOptionsClearAjax", new { id = Model.ID }))';
jQuery.post(url, function(data) {
$selectedRow = null;
selectedRowIndex = -1;
gridAnswerOptions.refresh();
});
}
}

// AnswerOptions Events

function AnswerOptions_onDataBound(e) {
var grid = jQuery(e.target).data('tGrid');
grid.updateFilter('Code', 'AnswerAbbr');
grid.updateFilter('Value', 'AnswerText');

gridAnswerOptions = grid;

grid.updateEntityText('Value');
grid.updateEntityText('ImageType');

// update upload links
jQuery('.upload-icon-button').each(function () {
var $that = jQuery(this);
$that.click(function (e) {
if (e.preventDefault) e.preventDefault();

// select the row the anchor is in
var $tr = $that.parents('tr').first();
$tr.click();

// show the window
jQuery('#UploadWindow').data('tWindow').center().open();
});
});

// update icon src
jQuery('.answer-option-icon').each(function () {
var $that = jQuery(this);
var src = $that.attr('src');
var $tr = $that.parents('tr').first();
var rowIndex = $tr[0].sectionRowIndex;
$that.attr('src', src.replaceIndexParam(rowIndex));
});

// hide edit-related update/cancel
jQuery('.entity-action-update, .entity-action-cancel').each(function () {
jQuery(this).hide();
});

// check if selectedRowIndex is set and select that row
if (selectedRowIndex >= 0) {
grid.selectRow(selectedRowIndex);
selectedRowIndex = -1;
}
// check if it's a newly created AnswerOption and set into edit mode
if (isNewAnswerOption) {
jQuery('#editAnswerOption').click();
isNewAnswerOption = false;
}
}

function AnswerOptions_onRowSelect(e) {
/* persist any row changes locally
jQuery('.t-grid-edit-row').each(function () {
gridAnswerOptions.overrideUpdateRow(jQuery(this));
selectedRowIndex = e.row.sectionRowIndex;
gridAnswerOptions.refresh();
});*/

$selectedRow = jQuery(e.row);
var rowIndex = e.row.sectionRowIndex;
var tr = ($selectedRow.data('tr') || $selectedRow)[0];
var dataItem = gridAnswerOptions.dataItem(tr);

// update buttons and state
enableButton(jQuery('#editAnswerOption'));

enableButton(jQuery('#moveUpAnswerOption'));
enableButton(jQuery('#moveDownAnswerOption'));
if (rowIndex == 0)
disableButton(jQuery('#moveUpAnswerOption'));
else if (rowIndex == e.row.parentElement.children.length - 1)
disableButton(jQuery('#moveDownAnswerOption'));

if (dataItem.Enabled === true)
jQuery('#toggleEnableAnswerOption').find('img:first').attr('src', '@Url.Content("~/Content/Common/Images/Icons/accept.png")');
else
jQuery('#toggleEnableAnswerOption').find('img:first').attr('src', '@Url.Content("~/Content/Common/Images/Icons/disabled.png")');

enableButton(jQuery('#toggleEnableAnswerOption'));
enableButton(jQuery('#deleteAnswerOption'));
}

function AnswerOptions_onGridSave(e) {
var values = e.values;
if (!values.Picture) {

values.Picture = lastUploadedFile;
gridAnswerOptions.refresh();
}
}


// UploadWindow Events

function UploadWindow_onOpen(e) {
// remove any uploaded files--just remove the ul containing the list, the reupload will still work
// jQuery('ul.t-upload-files').remove();

}

// UploadIcon Events
function UploadIcon_onLoad(e) {
// change the Select... text
jQuery(e.target).find('.t-upload-button span').html('Select icon...');
}

function UploadIcon_onSelect(e) {
// select the row the anchor is in
var $tr = jQuery(this).parents('tr').first();
$tr.click();
}

function UploadIcon_onRemove(e) {
var rowIndex = $selectedRow[0].sectionRowIndex;
e.data = { id: '@Model.ID', index: rowIndex };
}

function UploadIcon_onError(e) {
if (e.response) {
var data = e.response;
alert(data.error.message);
}
}
//]]>
</script> 

Controller:
[HttpPost]
public JsonResult _AnswerOptionsMoveRow(Guid id, int index, int? num)
{
if (index < 0)
index = 0;

if (num == null)
num = -1;

var newIndex = index + (int)num;
var ao = Attribute.AnswerOptions[index];
Attribute.AnswerOptions.RemoveAt(index);
Attribute.AnswerOptions.Insert(newIndex, ao);

return Json(new { index = newIndex, answerOption = ao });


Model:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Script.Serialization;

namespace ACS.CSG.ReviewContentManager.Models
{
public class AnswerOptionViewModel : BaseViewModel
{
[Key]
[ReadOnly(true)]
[ScaffoldColumn(false)]
[DisplayName("Id")]
public int ID { get; set; }

[DisplayName("Code")]
[StringLength(10)]
public string AnswerAbbr { get; set; }

[Required(AllowEmptyStrings = false)]
[DisplayName("Value")]
[StringLength(200)]
public string AnswerText { get; set; }

public int? AnswerValue { get; set; }

[DisplayName("ImageType")]
public LookupViewModel ImageType { get; set; }
public string ImageTypeValue
{
get { return (ImageType == null) ? "" : ImageType.ColumnValue; }
set
{
if (String.IsNullOrEmpty(value) == false)
{
var lookup = LookupViewModel.GetLookup("AnswerOption", "ImageType", value) ??
LookupViewModel.GetLookup("AnswerOption", "ImageType", "image/bmp");

ImageType = lookup;
}
else
ImageType = null;
}
}

//[ScriptIgnore]
public byte[] RelatedImage
{
get;
set;
}

[DisplayName("Image")]
public string RelatedImageId
{
get { return ID.ToString(); }
}

[Required]
public Int16 Ordinal { get; set; }

[Required]
public bool Enabled { get; set; }

public void ToggleEnabled()
{
Enabled = !Enabled;
}

//[Required]
//public AttributeViewModel Attribute { get; private set; }

public static AnswerOptionViewModel CreateAttributeValue()
{
var answerOption = new AnswerOptionViewModel();

answerOption.ID = 45;
answerOption.AnswerText = null;
answerOption.AnswerAbbr = null;
answerOption.AnswerValue = null;
answerOption.Ordinal = 1;
answerOption.RelatedImage = null;
answerOption.ImageType = null;
answerOption.Enabled = true;


return answerOption;
}
}
}

Any suggestions you could provide would be greatly appreciated. 
Jamie
Top achievements
Rank 1
 asked on 11 Jul 2012
2 answers
228 views

Hello -- we are building a large number of widgets that either extend Kendo UI widgets or have similar APIs, and it would be really nice to generate Kendo UI-like HTML documentation using JSDoc.  However, a number of the tags used in the Kendo UI code are not standard JSDoc syntax.  As Kendo tweeted here:

http://twitter.com/KendoUI/statuses/173019911008960512

"we use a modified jsDoc template that parses our configuration objects (that are passed to the jQuery plug-ins)"

Is there any chance this JSDoc template could be made available so that Kendo UI users could employ the same documentation patterns to promote consistency and compatibility?  Thanks!

ryan
Ryan
Top achievements
Rank 1
 answered on 11 Jul 2012
1 answer
140 views
How can I hide the address bar... typical javascript methods such as scrollTo stop working as soon as I make it a Kendo UI Mobile application. See sample here where i used the hideAddressBar option that I found in documentation somewhere that also does NOT work.


Kamen Bundev
Telerik team
 answered on 11 Jul 2012
0 answers
126 views
I Like to use a Chart in my website...
and use this chart with datasource to my "wcf data service".


// DataSource
//#########################
 
 $(document).ready(function () {
 
 
        var remoteDataSource = new kendo.data.DataSource({
            type: "odata",
            transport: {
                read: "http://localhost:1674/WcfDataService1.svc/Stats"
            }
        });
 
        remoteDataSource.read();
 
 
 
// Chart
//#########################
                   
$("#chart").kendoChart({
            title: {
                text: "Kendo Chart Example"
            },
            dataSource: {
                data: remoteDataSource
            },
            series: [{
                name: "Customers",
                field: "Customers"
            }],
            categoryAxis: {
                field: "Datum"
            }
        });
 
    });



The Dataservice and the Datasource works but my chart throw each times an error:
"Uncaught TypeError: Object [object Object] has no method 'slice'" but why??

If i use the same datasource with a gridview it works very fine :(
dravus peter
Top achievements
Rank 1
 asked on 11 Jul 2012
Narrow your results
Selected tags
Tags
Grid
General Discussions
Charts
Data Source
Scheduler
DropDownList
TreeView
MVVM
Editor
Window
DatePicker
Spreadsheet
Upload
ListView (Mobile)
ComboBox
TabStrip
MultiSelect
AutoComplete
ListView
Menu
Templates
Gantt
Validation
TreeList
Diagram
NumericTextBox
Splitter
PanelBar
Drag and Drop
Application
Map
ToolTip
Calendar
PivotGrid
ScrollView (Mobile)
Toolbar
TabStrip (Mobile)
Slider
Button (Mobile)
Filter
SPA
Drawing API
Drawer (Mobile)
Globalization
LinearGauge
Sortable
ModalView
Hierarchical Data Source
Button
FileManager
MaskedTextBox
View
Form
NavBar
Notification
Switch (Mobile)
SplitView
ListBox
DropDownTree
PDFViewer
Sparkline
ActionSheet
TileLayout
PopOver (Mobile)
TreeMap
ButtonGroup
ColorPicker
Pager
Styling
Chat
MultiColumnComboBox
Dialog
DateRangePicker
Checkbox
Timeline
Drawer
DateInput
ProgressBar
MediaPlayer
ImageEditor
TextBox
OrgChart
Accessibility
Effects
PivotGridV2
Licensing
ScrollView
Switch
TextArea
BulletChart
QRCode
ResponsivePanel
Wizard
CheckBoxGroup
Localization
Barcode
Breadcrumb
Collapsible
MultiViewCalendar
Touch
RadioButton
Stepper
Card
ExpansionPanel
Rating
RadioGroup
Badge
Captcha
Heatmap
AppBar
Loader
Security
TaskBoard
Popover
DockManager
TimePicker
FloatingActionButton
CircularGauge
ColorGradient
ColorPalette
DropDownButton
TimeDurationPicker
ToggleButton
BottomNavigation
Ripple
SkeletonContainer
Avatar
Circular ProgressBar
FlatColorPicker
SplitButton
Signature
Chip
ChipList
VS Code Extension
AIPrompt
PropertyGrid
Sankey
Chart Wizard
OTP Input
SpeechToTextButton
InlineAIPrompt
StockChart
ContextMenu
DateTimePicker
RadialGauge
ArcGauge
AICodingAssistant
SmartPasteButton
PromptBox
SegmentedControl
+? more
Top users last month
Hiba
Top achievements
Rank 1
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Max
Top achievements
Rank 1
Veteran
Iron
Alina
Top achievements
Rank 1
Rakhee
Top achievements
Rank 1
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Hiba
Top achievements
Rank 1
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Max
Top achievements
Rank 1
Veteran
Iron
Alina
Top achievements
Rank 1
Rakhee
Top achievements
Rank 1
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?