How to send data to Kendo Grid? - ajax

My goal is to have an input text box with two buttons that will perform different database queries with the input and then output the results to the Kendo Grid. Could someone please show me an example or point out what I am doing wrong? I would like to use Ajax as, from my limited understanding, this would prevent a full page reload.
View code:
<div class="loginForm">
<div id="searchForm" class="well">
<h2>Search</h2>
<form method="post" action="~/Search/Search">
<input type="text" id="search" name="input" class="form-control input-group input-group-lg" placeholder="Search..." required autofocus/>
<br />
<input type="submit" id="bunNumBut" name="submitBut" class="btn btn-primary btn-sm pull-left" value="Bundle Number" />
<input type="submit" id="custNumBut" name="submitBut" class="btn btn-primary btn-sm pull-right" value="Customer Number" />
</form>
</div>
</div>
<br />
<div>
{
#(Html.Kendo().Grid(Model)
.Name("searchResultsG")
.Columns(columns =>
{
columns.Bound(c => c.BundleNumber);
columns.Bound(c => c.CustomerNumber);
columns.Bound(c => c.Carrier);
columns.Bound(c => c.Active);
})
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.Sortable()
.Editable()
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read
.Action("Bundles_Read", "Search")
.Data("bundlesReadData"))
.Model(model => model.Id(p => p.CustomerNumber)))
)
}
</div>
<script>
function bundlesReadData() {
return {
input: $('#search').val()
};
}
</script>
Controller code:
[HttpPost]
public ActionResult Search(string input, string submitBut)
{
searchInput = input; //private class variables, but they get erased on each request
submitButton = submitBut; //private class variables, but they get erased on each request
switch (submitButt)
{
case "Bundle Number":
return View("Index");
case "Customer Number":
return View("Index");
default:
return View("Index");
}
}
public ActionResult Bundles_Read([DataSourceRequest]DataSourceRequest request)
{
if (searchInput == "Bundle Number")
return Json(GetBundlesByBunNum(searchInput).ToDataSourceResult(request));
else
return Json(GetBundlesByCustNum(searchInput).ToDataSourceResult(request));
}
I don't know how to pass the input and submitBut to the javascript function bundlesReadData() since I would like to pass in conditional data to the Bundles_Read() method. I also don't know what this DataSourceRequest object is doing and it is preventing me from calling the GetBundlesByBunNum() and GetBundlesByCustNum() methods in my Search() method. Let me know if anything is unclear or if I need to provide more details to help you help me.

If you have already returned all your data then instead of making additional ajax requests to filter the results you could use kendo's filter functionality with a single textbox.
When the user enters something in the textbox field the grid filters the results searching if the BundleNumber or CustomerNumber contains the user input field value.
<div class="loginForm">
<div id="searchForm" class="well">
<h2>Search</h2>
<input type="text" id="search" name="input" class="form-control input-group input-group-lg" placeholder="Search..." required autofocus/>
</div>
</div>
<script type="text/javascript">
$(function()
{
$('#search').on('input', function()
{
var value = $(this).val();
if (value)
{
$("#searchResultsG").data("kendoGrid").dataSource.filter(
{
logic: "or",
filters:
[
{ field: "BundleNumber", operator: "contains", value: value },
{ field: "CustomerNumber", operator: "contains", value: value }
]
});
}
else
{
$("#searchResultsG").data("kendoGrid").dataSource.filter({});
}
});
});
</script>

Related

"TypeError: Cannot read property 'title' of undefined" in form

An error is returned when I try to post the form.
The form is in a component, and the same structure is used in another component but does not generate any error.
I tried to find the mistake by myself but impossible to find the solution.
<template>
<div class="card" style="width: 18rem;margin:0 0 1rem 1rem;">
<div class="card-body">
<h4 class="mt-3 text-center" style="cursor:pointer;" #click="show=!show" >Add list</h4>
<form v-show="show" #submit.prevent="submitList">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" :class="{'is-invalid':errors.title}" v-model="form.title"/>
<p class="text-danger" v-if="errors.title" v-text="errors.title[0]"></p>
</div>
<button type="submit" class="btn btn-lg btn-success mb-4">Submit</button>
</form>
</div>
</div>
</template>
<script>
export default {
data() {
return {
show : false,
form: {
title: '',
},
errors: {}
}
},
methods: {
submitList() {
axios.post('/list', this.form)
.then(({data}) => {
this.$emit('newList', data),
this.form.title = '',
this.show = false,
this.errors = {}
})
.catch(error => {
this.errors = error.response.data.errors
})
}
}
}
</script>
Error in render: "TypeError: Cannot read property 'title' of undefined"
Reference this at the start of the method submitList and then use the reference in the axios response.
let that = this;
then that.form.title;
submitList () {
let that = this;
axios.post('/list', this.form)
.then(({ data }) => {
that.$emit('newList', data),
that.form.title = '',
that.show = false,
that.errors = {}
})
.catch(error => {
that.errors = error.response.data.errors
})
}
There's not really enough information here to answer the question. Since it's a render issue my guess is that it's one of these lines:
<input type="text" class="form-control" :class="{'is-invalid':errors.title}" v-model="form.title"/>
<p class="text-danger" v-if="errors.title" v-text="errors.title[0]"></p>
The question is what you get from the backend in your catch method. You should probably log that value and check that it's formated the way you think it is.
A nice tool for debugging Vue is the browser extension, maybe it will help with clearing up the problem.
If this does not solve your problem you need to provide more info:
When does the error occur
What is the value of the data-properties when it occurs
Maybe a screenshot of a more thorough error-message

Kendo UI grid, search box in toolbar in mvc

Kendo-grid search box in toolbar in mvc with razor syntax,
I am facing i need toolbar in which searching box , this searching box search into grid data.
Just copy and paste this code bind with mvc model and custom button(CRUD) and search box in toolbar in kendo grid template
<div>
#(Html.Kendo().Grid(Model)
.Name("DiagnosisTestGrid")
.Columns(columns =>
{
columns.Bound(c => c.Description).Title("Description");
columns.Bound(c => c.Cost).Title("Cost");
columns.Bound(c => c.CostingRequired).Title("Cost Req.");
columns.Bound(c => c.DxTestId).ClientTemplate(#"
<a href='/DiagnosisTest/Details/#=DxTestId#' class = 'dialog-window'>Detail</a> |
<a href='/DiagnosisTest/Edit/#=DxTestId#' class = 'dialog-window' >Edit</a> |
<a href='/DiagnosisTest/Delete/#=DxTestId#' class = 'dialog-window'>Delete</a>
").Title("");
})
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
<div class="row">
<div class="col-md-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></span>
<input type="text" class="form-control" id='FieldFilter' placeholder="Search for...">
<span class="input-group-btn">
<button class="btn btn-default" type="button"><span class="glyphicon glyphicon-refresh" aria-hidden="true"></span></button>
</span>
</div>
</div>
</div>
</div>
</text>);
})
.Resizable(resizing => resizing.Columns(true))
.Sortable(sorting => sorting.Enabled(true))
.Reorderable(reorder => reorder.Columns(true))
.Pageable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(5)
.ServerOperation(false)
))
</div>
Script for search box. and filter grid items
<script>
$(document).ready(function () {
$("#FieldFilter").keyup(function () {
var value = $("#FieldFilter").val();
grid = $("#DiagnosisTestGrid").data("kendoGrid");
if (value) {
grid.dataSource.filter({ field: "Description", operator: "contains", value: value });
} else {
grid.dataSource.filter({});
}
});
});
I know this is a bit of an old question now but it seems like the accepted answer is quite limited. This is how I got my searchbox added into the toolbar.
.ToolBar(toolBar => toolBar.Template(#<text><input class='k-textbox' value="Search..." onfocus="if (this.value=='Search...') this.value='';" onblur="this.value = this.value==''?'Search...':this.value;" id='searchbox'/></text>))
Then the script
<script type="text/javascript">
function addSearch() {
return { searchbox: $('#searchbox').val() };
}
$('#searchbox').keyup(function () {
$('#gridWorkflows').data('kendoGrid').dataSource.read();
});
</script>
This seems a bit simpler that what you are using currently.
Hope it helps.

CheckedNodes posted is always null

I have followed the tutorial and the documentation of kendo treeview but I have an instance where in I added hidden values into the checkbox template. The problem is when the submit button was clicked, the posted values is always null.
Here is my view
#using (Ajax.BeginForm("Projects", "Maintenance", FormMethod.Post,null))
{
<div class="treeview-back">
#Html.TextBoxFor(c => c.UserAccountID)
#(Html.Kendo().TreeView()
.Name("treeviewSiteList")
.DataTextField("Name")
.Checkboxes(checkboxes => checkboxes
.CheckChildren(true)
.TemplateId("treeview-checkbox-template")
)
.DataSource(dataSource => dataSource
.Read(read => read
.Action("UserProjectFolderList", "Maintenance", new { useraccount_id = Model.UserAccountID }))
)
)
</div>
<button type="submit" class="k-button">Save</button>
}
<script id="treeview-checkbox-template" type="text/kendo-ui-template">
<input type="checkbox" name="treeviewNodes[#= item.id#]" value="#= item.id # "/>
<input type="hidden" name="treeviewNodes[#= item.id #]" value="#= item.SiteID #"/>
</script>
Here is my view:
public ActionResult GetChecked(int[] treeViewNodes)
{
}

pass a value of the form from view to controller

how do i pass the value of the form, which is (i assume) a string of date to the controller...
here is my view:
<script type="text/javascript" language="javascript">
$(function () {
$(".datepicker").datepicker({ onSelect: function (dateText, inst) { $("FORM").submit(); },
altField: ".alternate"
});
});
</script>
#model IEnumerable<CorReservation.Models.Reservation>
#{
ViewBag.Title = "Index";
}
<div class="divRightSide">
<div>
<div class="datepicker">
</div>
<form action="/" title="fff">
<input type="text" class="alternate" readonly="readonly" />
</form>
</div>
// do something eg. foreach (var item in Model)
{ #Html.DisplayFor(modelItem => item.Date)}
here is my controller: i want to pass the date selected from the datepicker to the controller and then the controller would return an Ienumerable of reservations...
DateTime date = System.DateTime.Now;
private ReservationEntities db = new ReservationEntities();
public ViewResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string dateInput)
{
date = Convert.ToDateTime(dateInput);
var reservations = db.Reservations.Where(r=> r.Date ==date).Include(r => r.Employee).Include(r => r.Room).OrderByDescending(r => r.Date);
return View(reservations);
}
There are 2 ways to do this. Make the form input name attribute match the expected attribute in your controller.
For example:
<input type="text" class="alternate" readonly="readonly" name="dateInput" />
Or if there's going to be a lot of input values, use a Model.
It's automatically done based on the 'name' attribute of the HTML fields you want to submit.
Change your form to
<form action="/" title="fff">
<input name="dateInput" type="text" class="alternate" readonly="readonly" />
</form>
And it should work just like that.
Also, as you are using Razor syntax, you could use the Razor HTML helpers like so
#model IEnumerable<CorReservation.Models.Reservation>
#{
ViewBag.Title = "Index";
}
<div class="divRightSide">
<div>
<div class="datepicker">
</div>
#using(#Html.BeginForm("<your controller name>", "<your action name e.g. Index>"){
Html.TextBox("dateInput", "", new { #readonly="readonly", #class="alternate" })
}
</div>
// do something eg. foreach (var item in Model)
{ #Html.DisplayFor(modelItem => item.Date)}

autocomplete json

i have follow the following wave for autocomplete and datepicker but the auto complete can't work Secondly is there any razor syntax to show the datepicker and autocomplete
javascriptfile
/// <reference path="jquery-1.5.1-vsdoc.js" />
/// <reference path="jquery-ui-1.8.11.js" />
$(document).ready(function () {
$(":input[data-autocomplete]").each(function () {
$(this).autocomplete({ source: $(this).attr("data-autocomplete") });
});
$(":input[data-datepicker]").datepicker();
})
The View File
#model TestDateTimePicker.Models.TestClass
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>TestClass</legend>
<div class="editor-label">
#Html.LabelFor(model => model.City)
</div>
<div class="editor-field">
<input data-autocomplete="#Url.Action("AutoComplete", "City","City")" class="text-box single-line" id="City" name="City" type="text" value="" />
#Html.ValidationMessageFor(model => model.City)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Date)
</div>
<div class="editor-field">
<input class="text-box single-line" data-val="true" data-val-required="The Date field is required." id="Date" name="Date" type="text" value="" data-datepicker="true"/>
#Html.ValidationMessageFor(model => model.Date)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
The Json Controller
public ActionResult AutoComplete(String s)
{
var d = db.Cities
.Where(r => r.Name.Contains(s))
.Select(r => new { label = r.Name });
return Json(d, JsonRequestBehavior.AllowGet);
}
#Url.Action("AutoComplete", "City", "City")
should be
#Url.Action("AutoComplete", "City")
The third argument that you are using represents route values which must be an anonymous object and not a string. As far as the autocomplete plugin is concerned, it uses the term query string when performing the AJAX request to fetch the data. So you will have to rename your controller action parameter as well:
public ActionResult AutoComplete(string term)
{
var d = db.Cities
.Where(r => r.Name.Contains(term))
.Select(r => new { label = r.Name });
return Json(d, JsonRequestBehavior.AllowGet);
}
Also make sure that that jquery-ui-1.8.11.min.js script is referenced in your page (cannot see it in your code example).
If it still doesn't work make sure that the AutoComplete action doesn't throw an exception when performing the query. Also look with FireBug or Developer Tools if there aren't some javascript errors and if the AJAX request is correctly sent.
The key to this solution is: We need to use item.label name because the AJAX will return the value in list format so we need to extract the value as shown in the below example.
<html>
<head>
<title>Ajax</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
$("#myname").autocomplete({
source: 'emp.php',
select: function (event, ui) {
$("#myname").val(ui.item.label);
$("#myid").val(ui.item.id);
},
minLength: 0,
autoFocus: true,
});
});
</script>
</head>
<body>
<h2>Ajax Testing</h2>
<input name="myname" id="myname" type="text">
<input name="myid" id="myid" type="text">
</body>
</html>
-------------- Below is the code of PHP for emp.php page --------------------------
<?php
require_once 'connection.php';
$query = "SELECT myname as label , myid as id FROM emp WHERE name LIKE ? ORDER BY name";
$rsTable = sqlsrv_query($conn, $query,array('%'.$_REQUEST['term'].'%'));
while ($row_rsTable = sqlsrv_fetch_array($rsTable, SQLSRV_FETCH_ASSOC)) {
$emparray[] = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $row_rsTable);
}
echo json_encode($emparray);
sqlsrv_close($conn);
?>

Resources