Nikolay Kostov
Nikolay Kostov

Reputation: 16983

Use KendoUI tree view as input value

I am using Kendo UI TreeView along with Kendo UI MVC Wrappers in my ASP.NET MVC project.

I have HTML form in my view. Here is the code of my view:

<form method="POST" action="@Url.Action("Review")">
    @* ... *@
    @(Html.Kendo().TreeView()
        .Name("CategoryId")
        .DataTextField("Name")
        .DataSource(dataSource => dataSource
            .Read(read => read.Action("Categories", "ReviewCategories"))
        )
    )
    @* ... *@
    <input type="submit" class="btn btn-primary" value="Submit" />
</form>

The tree view is working perfectrly. Here is the code of Categories action:

public JsonResult Categories(int? id)
{
    var categories = this.forumCategoriesService.All()
       .Where(x => id.HasValue ? x.ParentId == id : x.ParentId == null)
       .Select(x => new { id = x.Id, Name = x.Title, hasChildren = x.Children.Any() });

    return this.Json(categories, JsonRequestBehavior.AllowGet);
}

The problem is that when I click submit button the form sends all data except the value of the selected CategoryId.

What is the most elegand way to make the Kendo UI TreeView send CategoryId when I submit the form?

(If there is no easy way to send it as an input value, I will accept any custom JavaScript code solutions)

Upvotes: 4

Views: 796

Answers (1)

Nikolay Kostov
Nikolay Kostov

Reputation: 16983

I've found a workaround.

First: Create hidden input with the desired parameter:

<input type="hidden" name="CategoryId" id="CategoryId" value="@Model.CategoryId" />

Second: Add on select event handler for the tree view:

@(Html.Kendo().TreeView()
    .Name("CategoryIdTreeView")
    .DataTextField("Name")
    .Events(ev => ev.Select("onCategorySelect"))     @* <--------------- *@
    .DataSource(dataSource => dataSource
        .Read(read => read.Action("Categories", "ReviewCategories"))
    )
)

Third: Implement the handler and change the value of #CategoryId in it

function onCategorySelect(ev) {
    var dataItem = this.dataItem(ev.node);
    var categoryId = dataItem.id;
    $("#CategoryId").val(categoryId);
}

If anyone knows better solution please be welcome to add another answer.

Upvotes: 2

Related Questions