i have a problem with a DropdownList control.
i have a Grid with a popup edditing and when i show a popup the DropDownList doesnt show any data, im using MVC4 and KendoUI controls
this is the code.
The Grid.
#(Html.Kendo().Grid<CashControl.Models.Usuario>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.nombre).Width(100);
columns.Bound(p => p.nombreUsuario).Width(100);
columns.Bound(p => p.email).Width(100);
columns.Command(command => { command.Edit(); command.Destroy(); }).Width(160);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("DropDownListUsuarios"))
.Pageable()
.Sortable()
.Scrollable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(p => p.idUsuario);
})
.Create(update => update.Action("EditingInline_Create", "Grid"))
.Read(read => read.Action("UsuariosRead", "Configuracion"))
.Update(update => update.Action("EditingInline_Update", "Grid"))
.Destroy(update => update.Action("EditingInline_Destroy", "Grid"))
)
)
The PopUp
<div class="demo-section" style="width: 250px;">
<h2>Products</h2>
#(Html.Kendo().DropDownList()
.Name("products")
.HtmlAttributes(new { style = "width: 250px" })
.DataTextField("nombre")
.DataValueField("idnombre")
.DataSource(source => {
source.Read(read =>
{
read.Action("UsuarioRead", "Configuracion");
});
})
)
</div>
<style scoped>
.demo-section {
width: 250px;
margin: 35px auto 50px;
padding: 30px;
}
.demo-section h2 {
text-transform: uppercase;
font-size: 1.2em;
margin-bottom: 10px;
}
</style>
and the Controller.
public ActionResult UsuarioRead([DataSourceRequest] DataSourceRequest request)
{
IQueryable<Usuario> products = CashControl.Usuario;
var rest = products.Select(n => new
{
idUsuario = n.idUsuario,
nombre = n.nombre,
nombreUsuario = n.nombreUsuario,
email = n.email
});
DataSourceResult result = rest.ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet);
}
and this is the JSON result
{"Data":[{"idUsuario":1,"nombre":"Eduardo","nombreUsuario":"Brakyo","email":"eduardomeji#gmail.com"}],"Total":1,"AggregateResults":null,"Errors":null}
i hope anyone can helpme.
Tankx :D
Please try with below code snippet.
Below code will help you to bind your Data in DropDownList but it will not work Kendoui Grid. Means you have create two separate method for Grid and DropDownList.
Controller
public ActionResult UsuarioRead()
{
IQueryable<Usuario> products = CashControl.Usuario;
var rest = products.Select(n => new
{
idUsuario = n.idUsuario,
nombre = n.nombre,
nombreUsuario = n.nombreUsuario,
email = n.email
});
return Json(products, JsonRequestBehavior.AllowGet);
}
Related
I'm trying to limit the dropdowns in my kendo grid to only contain Products that have been previously mapped to the company chosen in another cell in the row.
I've used a dynamic drop down editor template approach.
However, the ID passed to getCompanyId() is always null and therefore my dropdowns are always null.
View:
#(Html.Kendo().Grid<XXXAppXXX.Models.WeeklyRailPlan>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.WeekNumber);
columns.Bound(c => c.Company).ClientTemplate("#=(data.Company) ? Company.Name : 'Select Company...'#");
columns.Bound(c => c.ServiceCode);
columns.Bound(o => o.Product)
.ClientTemplate("#= (data.Product) ? Product.Name : 'Select Product'#")
.EditorTemplateName("DynamicDropDownList");
//etc
})
.ToolBar(toolbar => {
toolbar.Create();
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Filterable()
.Events(ev => ev
.Remove(#"function(e){setTimeout(function(){$('#grid').data('kendoGrid').dataSource.sync()})}")
)
.Sortable(sortable => {
sortable.SortMode(GridSortMode.SingleColumn);
})
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.Events(events => events.Error("error_handler"))
.Sort(p => { p.Add("WeekNumber").Descending(); })
.Model(model => model.Id(p => p.ID))
.Read(read => read.Action("WeeklyRailPlans_Read", "WeeklyRailPlanGrid"))
.Create(create => create.Action("WeeklyRailPlans_Create", "WeeklyRailPlanGrid"))
.Update(update => update.Action("WeeklyRailPlans_Update", "WeeklyRailPlanGrid"))
.Destroy(destroy => destroy.Action("WeeklyRailPlans_Destroy", "WeeklyRailPlanGrid"))
)
)
EditorTemplate called DynamicDropDownList.cshtml
<script type="text/javascript">
function getCompanyId() {
return { CompanyID: '#=ID#' };
}
</script>
#(Html.Kendo().DropDownList()
.Name("Product")
.DataValueField("ID")
.DataTextField("Name")
.DataSource(ds => ds
.Read(read => read.Action("GetProductsForCompany", "Products").Data("getCompanyId")))
)
Controller method GetProductsForCompany (this is always receiving null)
public ActionResult GetProductsForCompany(int CompanyID)
{
return Json(db.Products.Where(e => e.Companies.Any(t =>t.ID == CompanyID)), JsonRequestBehavior.AllowGet);
}
I use code like this:
<script type="text/javascript">
function getCompanyId() {
var gview = $('#grid').data("kendoGrid");
var selectedItem = gview.dataItem(gview.select());
return { CompanyID: selectedItem.ID };
}
</script>
This solution required was:
function getCompanyId() {
var grid = $('#grid').data('kendoGrid');
var dataItem = grid.dataItem(grid.table.find('.k-edit-cell').parents('tr'))
return { CompanyID: dataItem.Company.ID };
}
I am new to Kendo UI. i have my code as follows.
#(Html.Kendo().Grid<ETS.Model.CompanyList>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.CompanyID).Title("Name").Template(#<text>#Html.ActionLink(#item.Name, "Company", "Companies", new { #id = #item.CompanyID }, new { #style = "color:black; text-decoration: none;" })</text>);
columns.Bound(p => p.City).Title("Billing City");
columns.Bound(p => p.SalesRep).Title("Sales Rep");
columns.Bound(p => p.Phone).Title("Company Name");
})
.Pageable(pageable => pageable
.PageSizes(true)
.ButtonCount(5)
.Refresh(true)
)
.Sortable()
.HtmlAttributes(new { style = "height: auto;" })
.BindTo(Model.Companies)
)
By default the there are 5 items displayed on the grid. Is there any way i can change that default value to 20 ?
Generally you would set the using the PageSize() function on your DataSource :
#(Html.Kendo().Grid<Product>()
.Name("grid")
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Products_Read", "Home"))
.PageSize(20)
)
)
or you could try limiting the available PageSizes() to just 20 :
.Pageable(pageable => pageable.PageSizes(new int[] {20}) ...)
Additionally, it can be set through the Javascript API via :
var grid = $("#grid").data("kendoGrid");
grid.dataSource.pageSize(20);
grid.refresh();
I thought I had everything working but realized when I clicked on the update button, the values from the custom editor are not getting passed to the controller. It's the original values from the select grid row.
My grid is defined as follows and loads data correctly.
#(Html.Kendo().Grid<ET.Data.Models.TowTicketModel>()
.Name("gridTicketStatus")
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => {
model.Id(p => p.TicketId);
model.Field(p => p.TicketId).Editable(false);
model.Field(c => c.CreatedDateTime).Editable(false);
model.Field(c => c.AssignedTo).Editable(false);
model.Field(c => c.TicketType).Editable(false);
model.Field(c => c.Customer.Name).Editable(false);
model.Field(c => c.Description).Editable(false);
// model.Field("TicketStatus", typeof(TowTicketStatusModel));
})
.Read(read => read.Action("GetTowTickets", "TowDriver"))
.Update(up => up.Action("UpdateTowDriverTickets", "TowDriver"))
)
.Columns(columns =>
{
columns.Bound(ticket => ticket.TicketId).Title("Id");
columns.Bound(ticket => ticket.CreatedDateTime).Title("Date").Width("120px").Format("{0:MM/dd/yyyy}")
.HeaderHtmlAttributes(new
{
//style = "white-space: nowrap; text-overflow: ellipis;"
#class = "k-grid td"
});
columns.Bound(ticket => ticket.Customer.Name)
.HeaderHtmlAttributes(new
{
//style = "white-space: nowrap; text-overflow: ellipis;"
#class = "k-grid td"
});
columns.Bound(p => p.TicketType)
.ClientTemplate("#: data.TicketType ? data.TicketType.DisplayValue : '' #")
.Title("Type")
.HeaderHtmlAttributes(new
{
//style = "white-space: nowrap; text-overflow: ellipis;"
#class = "k-grid td"
});
columns.Bound(p => p.TicketStatus)
.ClientTemplate("#: data.TicketStatus ? data.TicketStatus.DisplayValue : '' #")
.Title("Status")
.HeaderHtmlAttributes(new
{
//style = "white-space: nowrap; text-overflow: ellipis;"
#class = "k-grid td"
});
columns.Bound(ticket => ticket.Description).HeaderHtmlAttributes(new
{
//style = "white-space: nowrap; text-overflow: ellipis;"
#class = "k-grid td"
})
.HtmlAttributes(new { title = "#= Description #" });
columns.Bound(p => p.AssignedTo)
.ClientTemplate("#: data.AssignedTo ? data.AssignedTo.FullName : '' #")
.Title("AssignedTo")
.HeaderHtmlAttributes(new
{
//style = "white-space: nowrap; text-overflow: ellipis;"
#class = "k-grid td"
});
columns.Bound(ticket => ticket.CreatedBy.FullName).Title("CreatedBy").HeaderHtmlAttributes(new
{
//style = "white-space: nowrap; text-overflow: ellipis;"
#class = "k-grid td"
});
columns.Command(cmd => cmd.Edit());
//columns.Bound(ticket => ticket.AssignedTo.FullName).Title("AssignedTo");
// columns.Bound(ticket => product.UnitsInStock);
})
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("TowTicketDriverEditor"))
// .ToolBar(tb => tb.Save)
.Pageable()
.Sortable()
)
My Editor contains the following.
> #model ET.Data.Models.TowTicketModel
>
>
> #Html.HiddenFor(model => model.TicketId)
>
> <div class="container">
> <div class="row">
>
> <div>
> #Html.LabelFor(model => model.TicketId)
> </div>
>
> <div>
> #Html.LabelFor(model => model.Customer.Name)
>
> #Html.EditorFor(model => model.Customer.Name, new { htmlAttributes = new { disabled = "disabled", #readonly = "readonly" }
> })
> </div>
> <div>
> #(Html.Kendo().DropDownListFor(m => m)
> .Name("TicketStatus")
>
> .DataValueField("TicketId")
> .DataTextField("DisplayValue")
> .Value("StatusId") // .Value(Model.StatusId)
> .DataSource(source =>
> {
> source.Read("GetTowTicketStatuses", "TowDriver")
> .ServerFiltering();
> }))
> </div>
>
> </div> </div>
Finally my controller:
public async Task<ActionResult> UpdateTowDriverTickets([DataSourceRequest] DataSourceRequest request,
TowTicketModel updated)
{
if (updated != null && ModelState.IsValid)
{
await _towProvider.UpdateTowTicketAsync(new UpdateTowTicketRequest(updated));
}
return Json(ModelState.ToDataSourceResult());
}
Again my grid loads, I click the edit button, the popup opens and the dropdownlist is properly populated from the ajax call.
However, I select from the dropdown and click update, the model parameter of UpdateTowDriverTickets doesn't have the value selected from editor dropdown.
I do have a GridForeignKey.cshtml template defined. (Just copied a template from an example.)
An input would be appreciated.
Turns out we had the wrong value in the DataValueField. TicketId was the Id for the grid but not the ID for our dropdownlist. Corrected that and everything appears to be working.
I have this telerik grid in a asp.net mvc project
<div class="actualGrid" id="actualGrid">
#(Html.Kendo().Grid<AVNO_KPMG.Models.Bench>() //Bench Grid
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.name).Title("Bench").Filterable(ftb => ftb.Cell(cell => cell.Operator("startswith"))).Width(100);
columns.Bound(p => p.freeSeats).Title("Free Seats").Width(200).Filterable(ftb => ftb.Cell(cell => cell.Operator("gte"))).HtmlAttributes(new { #class = "FreeSeats" })
.ClientTemplate("<div class='barthingy'><div class='bars_text'><div class='seatsText'><span class=\"bookNotfull\"></span> <b>#=bookedSeats#</b> USED SEATS</div><div class='seatsText'><span class=\"bookfull\"></span> <b>#=freeSeats#</b> TOTAL OFSEATS</div></div><div id='bigbar'><div class='bigbar' style='width:100%; float:left; background-color:rgb(142, 188, 0);'><div ' style='float:right; width:#=bookedSeats *100 / seatsCount#%; background-color:rgb(255, 99, 71); height:16px ' class='b_#=name#' id='temp-log'></div></div></div></div>");
//buttons
columns.Command(command => { command.Custom("checkBench1 ").Text(" AM ").Click("doCheckIn"); command.Custom("checkBench 2").Text(" PM ").Click("doCheckIn"); command.Custom("checkBench3").Text("All Day").Click("doCheckIn"); }).HtmlAttributes(new { #class = "comms#=freeSeats# freeAM#=seatsCount - (bookings_am + bookings_allday)# freePM#=seatsCount - (bookings_pm + bookings_allday)# freeALLDAY#=freeSeats#" }).Title("Check in").Width(200);
})
.Pageable()
.Sortable()
.Scrollable(scrolling => scrolling.Enabled(false))
.Filterable(ftb => ftb.Mode(GridFilterMode.Row))
//.HtmlAttributes(new { style = "height:530px;" })
.Events(events => events.DataBound("onDataBound"))
.DataSource(dataSource => dataSource
.Ajax()
//.Sort(sort => sort.Add("freeSeats").Ascending())
.PageSize(10)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(p => p.id))
.Read(read => read.Action("GetBenches", "Deskcheckin"))
)
)
</div>
Everytime i press on of the buttons in the command column, the url gets a # in front of it, even if i set the buttons to do nothing.
my url is something like
http://www.aaaaaa.com/stuff
When i press one of the buttons i get
http://www.aaaaaa.com/stuff#
How can i disable this?
Please try with the below code snippet. For custom command button grid generate anchor control for same. By default it set href='#' and I have replaced it with href='javascript:void(0)'.
<div>
#(Html.Kendo().Grid<MvcApplication1.Models.Student>()
.Name("grid")
.Columns(columns =>
{
..........
..........
columns.Command(command => { command.Custom("checkBench1").Text("AM").Click("doCheckIn"); }).Title("Check in").Width(200);
})
.Events(events => events.DataBound("onDataBound"))
..........
..........
)
</div>
<script>
function doCheckIn() {
alert('a');
}
function onDataBound(arg) {
$("#.k-grid-checkBench1").attr('href', 'javascript:void(0)');
}
</script>
Let me know if any concern.
I'm using Kendo UI grid with ASP.NET MVC 4
#Html.Label("Status: ")<select id="drStaus" style="width:250px">
<option value="Open">Open</option>
<option value="Pending">Pending</option>
<option value="Other">Closed</option>
</select>
<br /><br />
#(Html.Kendo().Grid((IEnumerable<FeedBackDashBord.Models.FeedBack>)Model)
.Name("grid")
.Columns(columns => {
columns.Bound(o => o.id).Visible(false);
columns.Template(o => Html.ActionLink("Edit", "Edit", new { o.id })).ClientTemplate("Edit").Width(45);
columns.Bound(o => o.CurrentURL).Width("200px").Title("Reported URL");
columns.Bound(o => o.OS).Width("70px");
columns.Bound(o => o.Browser).Width("70px");
columns.Bound(o => o.UserAgent).Width("200px"); ;
columns.Bound(o => o.datetime).Title("Date Time").Width("100px");
columns.Bound(o => o.Description).Title("Description").Width("200px");
columns.Bound(o => o.Email).Width("150px");
columns.Bound(o => o.Status).Width("70px");
columns.Template(o => Html.ActionLink("Details", "Details", new { o.id })).ClientTemplate("Details").Width(65);
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.Groupable()
.HtmlAttributes(new { style = "height:900px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("AjaxGrid", "DashBoard").Data("additionalInfo"))
)
)
<script>
function additionalInfo() {
return {
status: $("#drStaus").val()
}
}
$("#drStaus").kendoDropDownList();
</script>
In the above code i have successfully bound the Kendo Grid to a data source. Now i need to implement the following scenario.
when a option value is selected from the "drStaus" dropdown, i want to pass the selected value to the kendogrid and reload the grid according to the selected value.
Try this solution, I use demo model property to bound grid.
In view
#(Html.Kendo().DropDownList()
.Name("drStatus")
.DataTextField("Text")
.DataValueField("Value")
.Events(e => e.Change("Change"))
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "Open",
Value = "Open"
},
new SelectListItem() {
Text = "Pending",
Value = "Pending"
},
new SelectListItem() {
Text = "Other",
Value = "Other"
}
})
.Value("Open")
)
#(Html.Kendo().Grid(Model)
.Name("grid")
.Columns(columns =>
{
columns.Bound(x => x.Name);
columns.Bound(x => x.Id);
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.Groupable()
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("AjaxGrid", "DashBoard").Data("additionalInfo"))
)
)
And in javaScript
var additionalDataObject;
function additionalInfo() {
var dropdownlist = $("#drStatus").data("kendoDropDownList");
additionalDataObject = {
status: dropdownlist.value()
};
return additionalDataObject;
}
function Change() {
var grid = $("#grid").data("kendoGrid");
var page = grid.dataSource._page;
reloadFilterParameters();
grid.dataSource.page(page);
}
function reloadFilterParameters() {
var dropdownlist = $("#drStatus").data("kendoDropDownList");
additionalDataObject = {
status: dropdownlist.value(),
};
}
I've implemented the above scenario using Kendo Grid ToolBar Template.
http://demos.kendoui.com/web/grid/toolbar-template.html
#(Html.Kendo().Grid((IEnumerable<FeedBackDashBord.Models.FeedBack>)Model)
.Name("grid")
.Columns(columns => {
columns.Bound(o => o.id).Visible(false);
columns.Template(o => Html.ActionLink("Edit", "Edit", new { o.id })).ClientTemplate("Edit").Width(45);
columns.Bound(o => o.CurrentURL).Width("200px").Title("Reported URL");
columns.Bound(o => o.OS).Width("70px");
columns.Bound(o => o.Browser).Width("70px");
columns.Bound(o => o.UserAgent).Width("200px"); ;
columns.Bound(o => o.datetime).Title("Date Time").Width("100px");
columns.Bound(o => o.Description).Title("Description").Width("200px");
columns.Bound(o => o.Email).Width("150px");
columns.Bound(o => o.Status).Width("70px");
columns.Template(o => Html.ActionLink("Details", "Details", new { o.id })).ClientTemplate("Details").Width(65);
})
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
<label class="category-label" for="category">Status:</label>
#(Html.Kendo().DropDownList()
.Name("drStaus")
.OptionLabel("All")
.DataTextField("Text")
.DataValueField("Value")
.AutoBind(false)
.Events(e => e.Change("categoriesChange"))
.DataSource(ds =>
{
ds.Read("ToolbarTemplate_Categories", "DashBoard");
})
)
</div>
</text>);
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.Groupable()
.HtmlAttributes(new { style = "height:900px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("AjaxGrid", "DashBoard").Data("additionalInfo"))
)
)
<script>
function additionalInfo() {
return {
status: $("#drStaus").val()
}
}
$("#drStaus").kendoDropDownList();
</script>
<script>
function categoriesChange() {
var value = this.value(),
grid = $("#grid").data("kendoGrid");
if (value) {
grid.dataSource.filter({ field: "Status", operator: "eq", value: value });//parseInt(value)
} else {
grid.dataSource.filter({});
}
}
</script>