Telerik Forums
UI for ASP.NET MVC Forum
1 answer
1.9K+ views
Hi,

I'm almost done with the code from the subject. The tree expands already to the given ID, but unfortunately it does not select the node given by ID

Edit: Just to clarify, because I read a few threads regarding this issue - I don't get any error messages nor do I get 'undefined' for any variables. The node just doesn't get selected.

function expandAndSelectNode(id, treeViewName) {
    // get the Kendo TreeView widget by it's ID given by treeviewName
    var treeView = $(treeViewName).data('kendoTreeView');
     
    // find node with data-id = id
    var item = $(treeViewName).find("li[data-id='" + id + "']").find(".k-in");
     
    // expand all parent nodes
    $(item).parentsUntil('.k-treeview').filter('.k-item').each(
                function (index, element) {
                    $(treeViewName).data('kendoTreeView').expand($(this));
                }
            );
     
    // get DataSourceItem by given id
    var nodeDataItem = treeView.dataSource.get(id);
 
    //get node within treeview widget by uid
    var node = treeView.findByUid(nodeDataItem.uid);

    $(treeView).select(node);
    //treeView.select(".k-item:last");
}

I also tried $(treeView).select(item), since it should already point to the <span> item I want to select anyway. This didn't work.
Then I tried tried $(treeView).select(item.closest('.k-item')), since it points to the parent <li> element, but this didn't work either.
 The uncommented line (treeView.select(".k-item:last")) was just for testing and works.

I'm a little bit stuck and glad about any hints.

Daniel
Telerik team
 answered on 16 Jul 2013
1 answer
489 views
Hi,

I'am trying to create a dropdownlist with a guid as id : 

Dim dropDownListFor = _htmlHelper.Kendo().DropDownListFor(Of Integer)(_expression) _
                                                     .BindTo(New SelectList(_collectionValeur, "Id", "Name")) _
                                                     .HtmlAttributes(_attributsHtml)

Id is a Guid 
Name is a String

But I'm having the following error :

System.InvalidOperationException: Templates can be used only with field access, property access, single dimension array index, or single-parameter custom indexer expressions.

Any help please ?
Daniel
Telerik team
 answered on 15 Jul 2013
1 answer
100 views
I have a grid for a model Departments. Departments has a foreign key field ParentDepartmentKey. The foreign key field correctly generates a dropdown list with Departmens listed. However, if you add a new department, it is added to the grid, but the dropdown in the foreign key field is not updated and does not update.

Is it possible to have the foreign key field update when an item is added to the grid?
Vladimir Iliev
Telerik team
 answered on 15 Jul 2013
1 answer
1.6K+ views
In my attempts to right align, and apply a {0:N} format to the Sum on a ClientFooterTemplate  in MVC, I've got this far, but the format is not applied:

columns.Bound(e => e.BookValue).Title("Book Value ($)")
        .ClientFooterTemplate("<div class=aright>#=sum#</div>").Format("{0:N}")
It's right aligned now, but still the sum is showing 7 decimal places.

Should I be doing anything to the Aggregate instead of in the ClientFooterTemplate   ?                    

Ideas?           
Kiril Nikolov
Telerik team
 answered on 15 Jul 2013
4 answers
273 views
Hi,

I'm having an issue with the Kendo Grid, using the MVC extensions.

I have a foreign key column defined which displays perfectly when the grid is shown.  However, on edit, the dropdown (provided by a copy of the GridForeignKey.cshtml editor template) does not select the correct value for the record.  This is the case whether we're using InCell, InLine or Popup editing.

To clarify, the dropdown shows all the correct available values, but the default is selected instead of the value in the record.

ViewModels:
public class BranchesViewModel
{
    public IQueryable<BranchViewModel> Branches { get; set; }
    public IEnumerable<RegionViewModel> Regions { get; set; }
}
 
public class BranchViewModel
{
    [Editable(false, AllowInitialValue = true)]
    [Required]
    [Display(Name="Id")]
    [HiddenInput(DisplayValue = false)]
    public int BranchId { get; set; }
 
    [Display(Name="GL Code", Order=2)]
    [Required]
    public string GLCode { get; set; }
 
    [Display(Name="Region", Order=3)]
    [Required]
    [UIHint("RegionForeignKey")]
    public int RegionId { get; set; }
 
    [Display(Name="Branch Name", Order=1)]
    [Required]
    public string BranchName { get; set; }
}
 
public class RegionViewModel
{
    public int RegionId { get; set; }
    public string RegionName { get; set; }
}

Index View:
<h2>Branches</h2>
 
@(Html.Kendo().Grid<BranchViewModel>()
      .Name("Branch")
      .Columns(col =>
                   {
                       col.Bound(m => m.BranchName);
                       col.Bound(m => m.GLCode).Width(200);
                       col.ForeignKey(m => m.RegionId, Model.Regions, "RegionId", "RegionName").Width(180);
                       col.Command(cmd => { cmd.Edit(); cmd.Destroy(); }).Width(180);
                   })
      .ToolBar(toolBar => toolBar.Create().Text("New Branch"))
      .Editable(edit =>
                    {
                        edit.Mode(GridEditMode.InLine);
                        edit.DisplayDeleteConfirmation(true);
                    })
      .Sortable()
      .DataSource(dataSource => dataSource
        .Ajax()
        .Batch(true)
        .ServerOperation(false)
        .Events(events => events.Error("errorHandler"))
        .Model(model => model.Id(b => b.BranchId))
        .Read(read => read.Action("Branch_Read", "Branch"))
        .Create(create => create.Action("Branch_Create", "Branch"))
        .Update(update => update.Action("Branch_Update", "Branch"))       
        .Destroy(destroy => destroy.Action("Branch_Delete", "Branch"))
    )
)

RegionForeignKey Partial (in Views/Branch/EditorTemplates/):
Note: this is what I'm using now, however if I revert to the GridForeignKey editor template the behaviour is the same.
@model int
 
@(Html.Kendo().DropDownListFor(m => m)
    .BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
)

Controller Actions:
public ActionResult Index()
{
    var model = new BranchesViewModel
                    {
                        Branches = _branchRepository.Get().Select(
                            b => new BranchViewModel
                                     {
                                         BranchId = b.Id,
                                         GLCode = b.GLCode,
                                         BranchName = b.BranchName,
                                         RegionId = b.RegionId
                                     }
                        ),
                        Regions = _regionRepository.Get().Select(
                            r => new RegionViewModel
                                     {
                                         RegionId = r.Id,
                                         RegionName = r.RegionName
                                     }
                        ).ToList()
                    };
     
    return View(model);
}
 
 
// Ajax for branches
public ActionResult Branch_Read([DataSourceRequest] DataSourceRequest request)
{
    var branches = _branchRepository.Get().Select(
        b => new BranchViewModel
                 {
                     BranchId = b.Id,
                     GLCode = b.GLCode,
                     BranchName = b.BranchName,
                     RegionId = b.RegionId
                 }
        );
    return Json(branches.ToDataSourceResult(request));
}

I've scoured a number of other forum posts and haven't been able to find an answer.  Any help you could give would be very welcome.
Vladimir Iliev
Telerik team
 answered on 15 Jul 2013
0 answers
390 views

I am using an editor template to provide custom behavior in my grid when a user edits a record.  The editor template .cshtml file is as follows:

@model string
@Html.TextBoxFor(s => s, new { id ="gradingSubItemGrade", @class="k-textbox" })
<script type="text/javascript">
    $(document).ready(function () {
        $('#gradingSubItemGrade').bind('keypress', function (e) {
            if (e.keyCode == 13) {
                var barcode = e.currentTarget.value;
                GetJSON('/API/CoinReferenceInformation/ByBarcode?barcode=' + barcode,
                    function (data) {
                        $('#gradingSubItemGrade').val(data.Grade + data.GradeNumber);
                    },
                    function () { });
            }
        });
    })
</script>

As you can probably see from the code sample, I am trying to send the text of the TextBox to a service (when [Enter] is pressed), then, upon receiving a response, override it with the results.

This almost works...the response comes back correctly, and the results are displayed in the TextBox.  However, what is saved is what the user entered, not what is returned by the service.

Are there additional steps I need to do to notify the grid that the text has changed?

*** EDIT ***

Sorry, I found my answer a few posts below here
Steven
Top achievements
Rank 1
 asked on 13 Jul 2013
4 answers
115 views
I'm trying to add a new record using GridEditMode.PopUp, but my methods are called incorrectly and sometimes not called at all.
My grid is declared like this:
@(Html.Kendo().Grid<DigiBob.AppServices.ViewModels.Governance.Duties.AdhocTaskViewModel>()
    .Name("Grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.ShortDescription).Width(50);
        columns.Command(command => { command.Edit(); command.Destroy(); }).Width(160);
    })
    .ToolBar(toolbar =>
    {
        toolbar.Create();
    })
    .Editable(ed=>ed.Mode(GridEditMode.PopUp).TemplateName("AdhocTask"))
    .Pageable()
    .Sortable()
    .Scrollable()
    .Filterable()  
    .DataSource(dataSource => dataSource   
        .Ajax()
        .PageSize(20)
        .Events(events => events.Error("error_handler"))
        .Model(model => model.Id(c => c.ID))
        .Create(update => update.Action("CreateAdhocTask", "Home"))
        .Read(read => read.Action("GetAllAdhocTasks", "Home"))
        .Update(update => update.Action("UpdateAdhocTask", "Home"))   
        .Destroy(update => update.Action("DestroyAdhocTask", "Home"))
        )   
)
With the Create method like this:
[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CreateAdhocTask([DataSourceRequest] DataSourceRequest request, AdhocTaskViewModel item)
        {
            if (item != null && ModelState.IsValid)
            {
                _adhocTaskRepository = new AdhocTaskRepository(_context);
                AdhocTask target = new AdhocTask();
                target.ShortDescription = item.ShortDescription;
                _adhocTaskRepository.Insert(target);
                _adhocTaskRepository.Save();
                item.ID = target.ID;
            }
 
            return Json(new[] { item }.ToDataSourceResult(request, ModelState));
        }
When I try to debug it, the code in the CreateAdhocTask method is not called consequtively.  Instead the debugger jumps up and down between the lines until it finally reaches the last }
Debugging it again makes it jump around again, but in a different order.  It seems to have a mind of it's own.  It's working fine for the Read method.

More confusing is that it also calls the CreateAdhocTask method for the Update method, although a different method is supposed to be called there.
Also, the DestroyAdhocTask is completely ignored.

What would cause this?
Atanas Korchev
Telerik team
 answered on 13 Jul 2013
3 answers
102 views
Hi,

Is it possible to stop the combo-box drop down from dropping down when a value is removed?

It can be reproduced on here http://demos.kendoui.com/web/combobox/api.html by selecting a value, highlighting it and pressing the delete key. The drop-down drops down, I would like to prevent that.

Because I have several drop-downs appearing above eachother and when the user is emptying the values, and trying to move to the next one down they are accidently selecting the values again. They can of course use tab and delete but I was curious as to whether this behaviour could be disabled.

Thanks
Emma
Petur Subev
Telerik team
 answered on 12 Jul 2013
1 answer
227 views
Hi everybody,

First of all, I'd like to say that I'm completely new to ASP.Net MVC and Kendo UI, and that I'm coming from the WPF world. That might give you some clues about the difficulties I'm facing here ;)

The scenario is quite basic, but I'm not able to achieve what I need to.
Let's image I have a form, that contains 4 search criteria.
- Start Date
- End Date
- Number
- String (city name)

From those 4 fields, I'm trying to feed a Grid in the same page (in AJAX), with data that is coming from an WCF webservice.

I've tried several ways to achieve this but everytime I'm facing a dead-en.

Here's a sample of my code.
The form:
@using (Ajax.BeginForm("UpdateSearchCriteria", "Home", new AjaxOptions() { HttpMethod = "post", OnSuccess = "Update" }))
{
    @(Html.Kendo().DatePickerFor(model => model.Criteria.StartDate)
        .Min(new DateTime(1900, 1, 1)) //Set min date of the datepicker
        .Max(new DateTime(2099, 12, 31)) //Set min date of the datepicker
        )
 
    @(Html.Kendo().DatePickerFor(model => model.Criteria.EndDate)
        .Min(new DateTime(1900, 1, 1)) //Set min date of the datepicker
        .Max(new DateTime(2099, 12, 31)) //Set min date of the datepicker
        )
    @(Html.Kendo().IntegerTextBoxFor(model => model.Criteria.Number).Min(1))
    
     
    @(Html.Kendo().AutoCompleteFor(model => model.Criteria.CityName)
              .Filter("contains")
              .MinLength(3)
              .BindTo(Common.Helpers.CityHelper.GetCityNames())
              .HighlightFirst(true)
              .IgnoreCase(true)
    )
    <input type="submit" value="Search!" />
}
The Grid :

@(Html.Kendo().Grid<Models.SearchResult>()
       .Name("SearchResultDataGrid")
       .Columns(columns =>
       {
           columns.Bound(p => p.Property.PropertyName).Title("Property");
           columns.Bound(p => p.Range).Title("Range");
           columns.Bound(p => p.Number).Title("Number");
       })
       .Sortable()
       .Scrollable()
       .AutoBind(false)
       .BindTo(Model.SearchResult)
       .DataSource(dataSource => dataSource // Configure the grid data source
         .Ajax() // Specify that ajax binding is used
         .Read(read => read.Action("Search", "Home")) // Set the action method which will return the data in JSON format
      )
   )

JS Update method

<script>
    function Update(response, status, data) {
        var grid = $("#SearchResultDataGrid").data("kendoGrid");
        grid.dataSource.read();
    }
    </script>

Now the controller:

public ActionResult UpdateSearchCriteria(Screen iModel)
        {
            return Json(iModel);
        }
[HttpPost]
        public ActionResult Search(Screen iModel)
        {
            [...]
            return Json(theDataSourceRS);
        }
Obviously, when entering the Search Action, my iModel isn't updated with the latest data from the form. That's the main painpoint I have since the process I'm doing with the WCF service call doesn't have the correct Search criteria.

Hope I was clear enough !
Let me know if you're missing parts to give me a hand !

Thanks a lot !

Julien.
Petur Subev
Telerik team
 answered on 12 Jul 2013
5 answers
181 views
I'm wanting to put an HTML element in the HeaderTemplate() of a bound column.  I want to handle the click event of this HTML element.  This works fine as long as I have sorting turned off for the column.  However, if I have sorting turned on, then it seems that the grid automatically consumes the click of my HTML element and POSTs a sort on that column.  Is that by design?

If so, is there any way around it?  Turning off sorting for the column is not an option.  Is there a way to perform sorting from within the HeaderTemplate() that will also honor all other sorts/filters/paging/grouping on the grid?

If not that, is there a way to inject an HTML element via client-side code after the page has loaded that will not cause the column to sort when clicked?

I have tried both methods above but can't get them to work.  I'm hoping I'm missing something straightforward.
Dimiter Madjarov
Telerik team
 answered on 12 Jul 2013
Narrow your results
Selected tags
Tags
+? more
Top users last month
Will
Top achievements
Rank 2
Iron
Motti
Top achievements
Rank 1
Iron
Hester
Top achievements
Rank 1
Iron
Bob
Top achievements
Rank 3
Iron
Iron
Veteran
Thomas
Top achievements
Rank 2
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Will
Top achievements
Rank 2
Iron
Motti
Top achievements
Rank 1
Iron
Hester
Top achievements
Rank 1
Iron
Bob
Top achievements
Rank 3
Iron
Iron
Veteran
Thomas
Top achievements
Rank 2
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?