I have written controller as follow:
public class CommodityController : Controller
{
public ActionResult Vessel()
{
return View();
}
[GridAction]
public ActionResult SelectVessel()
{
var query = _productServices.GetAllProducts().ToList();
var model = PreparedBasicProductModel(query);
return View(new GridModel(model));
}
}
and I have written a view as follow:
#using Telerik.Web.Mvc.UI;
#using Telerik.Web.Mvc;
#model List<VesselSelection.Models.Vessel.ProductModel>
#(Html.Telerik().Grid<VesselSelection.Models.Vessel.ProductModel>()
.Name("Grid")
.DataBinding(dataBinding => dataBinding.Ajax().Select("SelectVessel", "Commodity")
)
.DataKeys(keys => keys.Add(c => c.Id))
.Columns(columns =>
{
columns.Bound(c => c.Id).Title("Picture");
columns.Bound(c => c.Name).Title("Data");
columns.Bound(c => c.ProductPicture).Title("Command");
})
.ClientRowTemplate(grid => "<div class='employee-details'>" +
"<img class='t-widget' src='<#= ProductPicture #>' alt='<#= Name #>' title='<#= Name #>' />" +
"<dl>" +
"<dt>Weight:</dt><dd><#= Weight #></dd>" +
"<dt>Cost Price:</dt><dd><#= CostPrice #></dd>" +
"<dt>Vendor:</dt><dd><#= VendorName #></dd>" +
"<div class='commands'>" + grid.EditButton(null) + grid.DeleteButton(null) + "</div>" +
"</div>"
)
.Sortable()
.Editable(editing => editing.Mode(GridEditMode.PopUp))
.Scrollable(scrolling => scrolling.Height(500))
.Pageable()
)
My question is that when i run this application data is not binding, so that in grid it showing blank.
please help me.
Have you tried using .OperationMode(GridOperationMode.Client) in your databinding?
Example:
.DataBinding(dataBinding => dataBinding.Ajax()
.OperationMode(GridOperationMode.Client)
.Select("SelectVessel", "Commodity")
)
You could always check the
online documentation from telerik when in doubt.
Related
I'm trying to update 2 dependent dropdowns simultaneously based on the value of the primary dropdown. Is it possible, if yes, what's wrong in my code? Correct, please.
Maybe it's better to use ASP.NET cascading dropdowns possibilites? If yes, how to do it with 3 dropdowns ?
View
#model RKB.Models.CountryStateViewModel
<br /><br/>
#using (Html.BeginForm("Index", "Home"))
{
<div class="container">
<div class="form-group">
#if (ViewBag.CountryList != null)
{
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "Выберите страну", new { #class = "form-control" })
}
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "Выберите штат", new { #class = "form-control" })
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.PriceId, new SelectList(" "), "Выберите цену", new { #class = "form-control", #style = "display:none" })
</div>
<button type="submit">Send</button>
</div>
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "</option>")
});
});
})
});
$(document).ready(function () {
$("#StateId").change(function () {
$.get("/Home/PriceList", { StateId: $("#StateId").val() }, function (data) {
$("#PriceId").empty();
$.each(data, function (index, row) {
$("#PriceId").append("<option value='" + row.PriceId + "'>" + row.Price1 + "</option>")
});
});
})
});
</script>
Controller
public class HomeController : Controller
{
RKBEntities db = new RKBEntities();
public ActionResult Index()
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
return View();
}
[HttpPost]
public ActionResult Index(CountryStateViewModel csm)
{
return View();
}
public JsonResult GetStateList(int CountryId)
{
db.Configuration.ProxyCreationEnabled = false;
List<State> StateList = db.States.Where(x => x.CountryId == CountryId).ToList();
return Json(StateList, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPriceList(int StateId)
{
db.Configuration.ProxyCreationEnabled = false;
List<Price> PriceList = db.Prices.Where(x => x.StateId == StateId).ToList();
return Json(PriceList, JsonRequestBehavior.AllowGet);
}
}
You have used the wrong property json, my friend.
For example: row.StateId => row.stateId.
Just try to modify following like this:
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.stateId + "'>" + row.stateName + "</option>")
});
});
})
});
$(document).ready(function () {
$("#StateId").change(function () {
$.get("/Home/PriceList", { StateId: $("#StateId").val() }, function (data) {
$("#PriceId").empty();
$.each(data, function (index, row) {
$("#PriceId").append("<option value='" + row.priceId + "'>" + row.price1 + "</option>")
});
});
})
});
</script>
Hope to help, my friend :))
I'm using kendo grid with checkbox client template and I would like to pass the row to a function.
<div>
#(Html.Kendo().Grid(Model).Name("EvaluationFormGrid").DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(m => m.EventEvaluationFormId);
model.Field(m => m.EventEvaluationFormId).Editable(false);
})
.Destroy(delete => delete.Action("DeleteEvaluationForm", "EvaluationFormsManagement"))
.PageSize(60)
.ServerOperation(false)
).Columns(c =>
{
c.Bound(m => m.EvaluationFormTitle).Width(150).Title("Evaluation Form Title");
c.Bound(m => m.EvaluationFormLink).Width(300).Title("Evaluation Form Link");
c.Bound(m => m.ModifiedUserName).Title("Mod. by").Width(80);
c.Bound(m => m.ModifiedDateUtc).Title("Mod. date").Width(80);
c.Bound(m => m.IsDisplayedInApp).Title("Is displayed in app").Width(80)
.ClientTemplate("<input type='checkbox' #= IsDisplayedInApp ? checked='checked' :'' # value='#=IsDisplayedInApp#' onClick='onChange(#=IsDisplayedInApp#)'/>");
c.Bound(m => m.EventEvaluationFormId).Title(string.Empty).Width(80)
.ClientTemplate("<a class='table-entry-control edit-entry-control' href='" + Url.Action("ManageEvaluationForm", "EvaluationFormsManagement",
new { area = "Admin" }) + "/#= EventEvaluationFormId #'" + "><span class=\"k-icon k-edit\"></span>Edit</a><br />")
.Sortable(false);
c.Command(commands =>
{
commands.Destroy();
}).Title("").Width(80);
})
.Events(events => events.Change("onChange"))
.Editable(e => e.DisplayDeleteConfirmation(true)).Deferred().DataSource(datasource =>
datasource
.Ajax()
.ServerOperation(false)).Deferred(true))
<script>
function onChange(arg) {
alert(arg);
var selected = $.map(this.select(), function (item) {
return $(item).text();
});
kendoConsole.log("Selected: " + selected.length + " item(s), [" + selected.join(", ") + "]");
}
</script>
</div>
With this line I would like to pass in the whole row, right now I only pass in a boolean:
c.Bound(m => m.IsDisplayedInApp).Title("Is displayed in app").Width(80)
.ClientTemplate("<input type='checkbox' #= IsDisplayedInApp ? checked='checked' :'' # value='#=IsDisplayedInApp#' onClick='onChange(#=IsDisplayedInApp#)'/>");
Does anyone know how I could pass row here:
onClick='onChange(#=IsDisplayedInApp#)
Thanks
Try this:
function onClick(chk) {
var grid = $('[name="EvaluationFormGrid"]').data("kendoGrid");
// Get the row
grid.dataItem($(chk).closest("tr"));
};
I'm not used to Kendo MVC so I don't know what .Name() generates, but in the first line of the function, you have to get the grid widgtet instance to the grid var.
I am making a code using ASP.NET MVC with kendo grid.
I want to bring the data from database to Kendo grid which equal to specific date or by default "today".
I want to make a datepicker and a button at the toolbar and everytime I click the button it send a request to the control and filter the data in LINQ and send the request for all the data in one day. I wrote this code:
Controller class:
//main method
public ActionResult LogAdminList()
{
return View();
}
//submethod for grid
public ActionResult Grid_ReadLogAdminList([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "id")] string date)
{
DateTime _temp;
if (!DateTime.TryParse(date, out _temp))
_temp = DateTime.Now;
return Json(_context.Entities<LogAdmin>().NoTracking().OrderByDescending(l => l.TimeStamp)
.Where(f => DbFunctions.TruncateTime(f.TimeStamp) == DbFunctions.TruncateTime(_temp))
.Select(l => new LogAdminInfo
{
Id = l.Id,
Message = l.Message,
MessageTemplate = l.MessageTemplate,
Level = l.Level,
TimeStamp = l.TimeStamp,
Exception = l.Exception,
Properties = l.Properties,
LogEvent = l.LogEvent,
})
.ToDataSourceResult(request));
}
the kendo code is :
#(Html.Kendo().Grid<LogAdminInfo>()
.BindTo(Model)
.Name("LogAdminList")
.Sortable()
.Columns(columns =>
{
columns.Bound(p => p.Message).Width(50).Title(WebResources.LogListMessage);
columns.Bound(p => p.MessageTemplate).Width(50).Title(WebResources.LogListMessageTemplate);
columns.Bound(p => p.Level).Title(WebResources.LogListLevel);
columns.Bound(p => p.TimeStamp).Title(WebResources.LogListTimeStamp).Format("{0:dd.MM.yyyy H:mm}");
columns.Bound(p => p.Exception).Width(50).Title(WebResources.LogListException);
columns.Bound(p => p.Properties).Width(50).Title(WebResources.LogListProperties);
columns.Bound(p => p.LogEvent).Title(WebResources.LogListLogEvent);
})
.Pageable(pageable => pageable
.Refresh(true)
.ButtonCount(5))
.HtmlAttributes(new { #class = "grd_UpcomingMilestone" })
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
<label class="category-label" for="category">#WebResources.LogFilterMessage</label>
#(Html.Kendo().DatePicker()
.Name("datepicker")
.Value(DateTime.Today)
.Format("dd.MM.yyyy")
)
#(Html.Kendo().Button()
.Name("filterButton")
.Icon("filter")
.Content("Filter")
.HtmlAttributes(new { type = "button" })
)
</div>
</text>);
})
.DataSource(source => source
.Ajax()
.Batch(true)
.ServerOperation(false)
.PageSize(100)
.Read(read => read.Action("Grid_ReadLogAdminList", "LogAdmin").Data("getFilterDate"))
))
I don't know what to do exactly in the javascript. the code works fine in the first request but not when I filter.
what should I write as a javascript?
thank you very much.
You have to pass data from client to server using getFilterDate function specified in you Kendo Grid Read Data method. Implement a function like this. The return type must be an object with fields with the same name you defined in your MVC Action, in this case date. Kendo will serialize them in order to build the get request:
function getFilterDate() {
var mydate = $("#datepicker").data("kendoDatePicker").value();
return {
"date": mydate
}
}
I'm trying to display a pop up window when a user clicks on a button but I cant seem to get this to work. I can fire the event when using a custom command but I need a textbox and button next to each other in the same column.
Any ideas why this isn't working?
#(Html.Kendo().Grid(Model)
.Name("gridPopup")
.Columns(columns =>
{
columns.Bound(p => p.ProductName).Width(120);
columns.Template(#<text></text>).Title("").Width(110).ClientTemplate(
Html.Kendo().TextBox()
.Name("search_textfield")
.Value("").ToClientTemplate().ToString()
+ " " +
Html.Kendo().Button()
.Name("search_button")
.HtmlAttributes(new { type = "button", #class = "k-primary" })
.Events(e =>
e.Click("SearchButton")
)
.Content("...").ToClientTemplate().ToString()
);
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Scrollable()
.HtmlAttributes(new { style = "height:320px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Events(events => events.Error("errorHandler"))
.Model(model =>
{
model.Id(p => p.ProductID);
model.Field(p => p.ProductID).Editable(true);
model.Field(p => p.CategoryID).DefaultValue(1);
})
.Read(read => read.Action("ForeignKeyColumn_Read", "Home"))
.Update(update => update.Action("ForeignKeyColumn_Update", "Home"))
.Create(create => create.Action("ForeignKeyColumn_Create", "Home"))
.Destroy(destroy => destroy.Action("ForeignKeyColumn_Destroy", "Home"))
)
)
<script type="text/javascript">
function errorHandler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
}
}
function SearchButton(e)
{
alert("Search Button Clicked");
}
</script>
Weird! .Events(e => e.Click("SearchButton")) is not generating the onclick attribute if used inside a ClientTemplate()
Try this, it will work for you, but i will wait for someone to explain it :)
.HtmlAttributes(new { type = "button", #class = "k-primary", onclick = "SearchButton()" })
Edit:
The explanation that I found is here: How do I use a Kendo UI widget inside a Grid client column template?. It says script tags are not automatically evaluated inside a Grid client column template, so any included widgets will not be initialized.
Therefore initializing the nested controls in .Events(e => e.DataBound("onDatabound"))
function onDatabound()
{
jQuery("#gridPopup tbody [class='k-primary']").each(function () {
$(this).kendoButton({ "click": SearchButton });
})
}
I'm using a Kendo UI Web Grid in an ASP.Net MVC 4 application.
At the bottom of the code below you'll see a JavaScript function called GetEditChildUrl that accepts a parameter called data. Unfortunately, what gets passed in as the data parameter is the parent row data but I was expecting the child row data. This works fine for GetEditParentUrl. So how do I get the child row data?
#(Html.Kendo().Grid<Application.Models.Parent>()
.Name("grid_parent")
.Columns(columns =>
{
columns.Bound(x => x.Name);
columns.Bound(x => x).ClientTemplate(
"<a href='#= GetEditParentUrl(data) #' class='k-button' style='min-width:0px;'><span class='k-icon k-i-pencil'></span></a>"
).Width(90).Filterable(false);
})
.Scrollable(action => action.Virtual(true))
.Filterable()
.Sortable()
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Parents_Read", "Parent"))
)
.Scrollable(s => s.Height("auto"))
.ClientDetailTemplateId("client-template")
)
#section Scripts {
<script id="client-template" type="text/x-kendo-template">
<h3>Contacts</h3>
#(Html.Kendo().Grid<Application.Models.Child>()
.Name("grid_child_#=Id#") // make sure the Name is unique
.Columns(columns =>
{
columns.Bound(x => x.Name);
columns.Bound(x => x).ClientTemplate(
"<a href='#= GetEditChildUrl(data) #' class='k-button' style='min-width:0px;'><span class='k-icon k-i-pencil'></span></a>"
).Width(90).Filterable(false);
})
.DataSource(dataSource =>
dataSource.Ajax().Read(read => read.Action("Children_Read", "Parent", new { parentId = "#=Id#" }))
)
.Scrollable(s => s.Height("auto"))
.Sortable()
.ToClientTemplate()
)
</script>
<script>
function GetEditParentUrl(data) {
return "#Url.Action("Edit", "Parent")/" + data.Id;
}
function GetEditChildUrl(data) {
return "#Url.Action("Edit", "Child")/" + data.Id;
}
</script>
}
Try escaping the hash (#) symbols in your column client template.
columns.Bound(x => x)
.ClientTemplate("<a href='\\#= GetEditChildUrl(data) \\#' ...>")
From the KendoUI docs:
Important: The "#" characters used for a template expression should be
escaped when using a column ClientTemplate in a detail template so
that the expression is evaluated in the correct context.