Multiple Kendo Grids in a Razor View - asp.net-mvc

I'm looping through my Model in a Razor View and wanted to display multiple Kendo Grids. However I'm getting all empty grids even though the Item_Read is being executed when the loop happens.
Any ideas?
Source:
#foreach (var itemM in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => itemM.id)
</td>
<td>
#(Html.Kendo().Grid<SomeOtherModel>()
.Name("KendoGrid" + itemM.id)
.Columns(columns =>
{
columns.Bound(p => p.title);
columns.Bound(p => p.details);
})
.AutoBind(true)
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(p => p.itemId);
model.Field(p => p.itemId).Editable(false);
})
.Read(read => read.Action("Item_Read", "Controller", new { id = itemM.id }))
)
)
</td>
</tr>
}

The problem was my ViewModel, one of the properties was null.

Related

Kendo grid client detail template rendering issue when using along with popup editor for update

Kendo grid client detail template not rendering properly when using pop up editor for update. I am using Detail template for displaying more columns and editor template for pop up edit. At first, if I open detail template it works fine but if I open popup editor for Add/Update, client detail template messed up and displays columns as in editing mode and layout disturbed as well. When second time popup editor opens, some of the columns styles messed up (such as not displaying numerictextbox).
What am I doing wrong here? Please advise.
At first Client detail template looks like this:
After clicking on edit button, the grid and pop up looks like as below:
My code is as below:
ClientDetailTemplate:
<script id="DisplayTemplate_Bonds" type="text/kendo-tmpl">
<div>
<table style="width:auto;">
<tr>
<td style="vertical-align:top;">
<table>
<tr id='Currency'>
<td>Currency</td>
<td>Equal To</td>
<td>#=CurrencyViewModel.ID#</td>
</tr>
<tr id='Classification'>
<td>Classification</td>
<td>Equal To</td>
<td>#=ClassificationBoardViewModel.Name#</td>
</tr>
<tr id='Maturity1'>
<td>Maturity</td>
<td>Equal To</td>
<td>#=kendo.toString(Maturity1, 'n2')#</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
Grid:
#(Html.Kendo().Grid<Models.Bonds_ViewModel>
()
.Name("Bonds_Grid")
.Columns(c =>
{
c.Bound(m => m.ID).Hidden();
c.Bound(m => m.FilterName)
.HtmlAttributes(new { #class = "gridDataColumns" })
.Title("Filter Name").HeaderHtmlAttributes(new { #title = "Filter Name" })
;
c.Command(p =>
{
p.Edit().Text(" ").UpdateText(" ").CancelText(" ").HtmlAttributes(new { #title = "Edit this filter" });
p.Destroy().Text(" ").HtmlAttributes(new { #title = "Delete this filter" });
});
})
.ToolBar(toolbar =>{toolbar.Create().Text("Add Filter").HtmlAttributes(new { #title = "Add" });})
.Editable(editable => editable
.Mode(Kendo.Mvc.UI.GridEditMode.PopUp)
.TemplateName("Editors/Bonds_Editor")
)
.DataSource(dataSource => dataSource
.Ajax()
.Model(m =>
{
m.Id(p => p.ID);
m.Field(p => p.CurrencyViewModel).DefaultValue(ViewData["DefaultCurrencyViewModel"] as Models.CurrencyViewModel);
m.Field(p => p.ClassificationBoardViewModel).DefaultValue(ViewData["DefaultClassificationBoardViewModel"] as Models.ClassificationBoardViewModel);
})
.Read(read => read.Action("Bonds_Read", "Phase1"))
.Create(create => create.Action("Bonds_Create", "Phase1"))
.Update(update => update.Action("Bonds_Update", "Phase1"))
.Destroy(destroy => destroy.Action("Bonds_Destroy", "Phase1"))
)
.ClientDetailTemplateId("DisplayTemplate_Bonds")
)
Popup editor:
#model Models.Bonds_ViewModel
#Html.HiddenFor(m => m.ID)
<table id="mainTable">
<tr>
<td>#Html.Label("Filter Name")</td>
<td>#Html.EditorFor(m => m.FilterName)</td>
<td> </td>
</tr>
<tr>
<td>#Html.Label("Currency")</td>
<td>#Html.EditorFor(m => m.CurrencyViewModel)</td>
<td> </td>
</tr>
<tr>
<td>#Html.Label("Classification")</td>
<td>#Html.EditorFor(m => m.ClassificationBoardViewModel)</td>
<td> </td>
</tr>
<tr>
<td>#Html.Label("Maturity")</td>
<td>#Html.Label("Equal To")</td>
<td>#(Html.Kendo().NumericTextBoxFor(m => m.Maturity1)
.HtmlAttributes(new { #class = "textboxFor_Styles", style = "width:90px;" })
.Format(GAM.BLL.GlobalVaribleDeclarations.DisplayFormatForDecimal)
.Spinners(true)
)
</td>
</tr>
</table>
I have found the issue here.
Actually, I had given the same id to the table rows in client detail template as the Controls (NumericTextboxes and others) id. I have changed the ids of the rows and all seems to be working fine.
e.g. in client detail template the row id for the Maturity is
<tr id='Maturity1'>
which was conflicting with the id assigned automatically to the Maturity NumerictextBox in Popup editor as
<td>#(Html.Kendo().NumericTextBoxFor(m => m.Maturity1)
.HtmlAttributes(new { #class = "textboxFor_Styles", style = "width:90px;" })
.Format(GAM.BLL.GlobalVaribleDeclarations.DisplayFormatForDecimal)
.Spinners(true)
)
</td>
Hope this will be helpful to others.

Kendo Grid MVC Compilation Error when loading cshtml file

I'm getting the following error when trying to load my .cshtml file:
Compiler Error Message: CS1026: ) expected
Source Error (Line 81):
Line 79: .AutoBind(true)
Line 80:
Line 81: .DataSource(dat​asource => datasource
Line 82: .Ajax()
Line 83: .Model(model =>
I have tried refreshing the cache and removing elements from the grid but it is still not working.
cshtml page code:
#{
var guid = Guid.NewGuid();
var layoutId = guid + "page-layout";
var partialModel = new Kendo_UI_Bootstrap_Integration.ViewModels.ReportLayoutViewModel();
partialModel.Title = "Report";
partialModel.ReportHeaderData = string.Format("<span id='{0}-start-date'>Start Date:</span><br/><span id='{0}-end-date'>End Date</span>", guid);
partialModel.Id = layoutId;
}
#Html.Partial(MVC.Reports.Views.ViewNames._ReportLayout, partialModel)
<input id="GuidInput" type="hidden" value="#guid" />
<table>
<tbody>
<tr>
<td>
<span>Start Date: </span>
#(Html.Kendo().DatePicker().Name(guid + "StartDate").Footer(false))
</td>
<td style="padding-left: 10px;">
<span>End Date: </span>
#(Html.Kendo().DatePicker().Name(guid + "EndDate").Footer(false))
</td>
#if (User.IsInRole("RearingUnitRearingManager") || User.IsInRole("BackOfficeSuperUser"))
{
<td style="padding-left: 10px;">
#(Html.Kendo().DropDownListFor(m => m)
.Name("dropdown")
.DataTextField("name")
.DataValueField("nameguid")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action(MVC.ControllerName.ActionNames.Action, MVC.Controller.Name))
.ServerFiltering(true);
})
.HtmlAttributes(new { style = "width: 306px;" })
)
</td>
}
<td style="padding-left: 10px;">
#(Html.Kendo().Button().Name("Submit").Content("Submit").Events(events => events.Click("submitbutton")))
</td>
</tr>
</tbody>
</table>
<br />
#(Html.Kendo().Grid<Kendo_UI_Bootstrap_Integration.Models.DTO.dto>()
.Name("gridname")
.ToolBar(tools => { tools.Pdf(); tools.Excel(); })
.Pdf(pdf => pdf
.AllPages()
.AvoidLinks()
.Landscape()
.TemplateId(layoutId)
.PaperSize("A4")
.Scale(0.6)
.RepeatHeaders()
.Margin("7cm", "1cm", "3cm", "1cm")
.FileName("pdf.pdf")
)
.Excel(excel => excel
.AllPages(true)
.FileName("excel.xlsx"))
.EnableCustomBinding(true)
.Columns(
columns =>
{
columns.Bound(c => c.item1).Hidden();
columns.Bound(c => c.item2);
columns.Bound(c => c.item3);
columns.Bound(c => c.item4);
columns.Bound(c => c.item5);
columns.Bound(c => c.item6);
}
)
.Editable(editable => editable.Mode(GridEditMode.InCell).DisplayDeleteConfirmation(false))
.AutoBind(true)
.DataSource(dat​asource => datasource
.Ajax()
.Model(model =>
{
model.Field(m => m.item1).Editable(false);
model.Field(m => m.item2).Editable(false);
model.Field(m => m.item3).Editable(false);
model.Field(m => m.item4).Editable(false);
model.Field(m => m.item5).Editable(false);
model.Field(m => m.item6).Editable(false);
})
.Group(group => group.Add(w => w.item1))
.Read(read => read.Action(MVC.Controller.ActionNames.Actionname_Read, MVC.Controller.Name).Data("function"))
.PageSize(100)
.Batch(true)
)
.Events(ev => ev.PdfExport("ProcessPdf").ExcelExport("SetExcelFileName"))
.HtmlAttributes(new { style = "z-index: 1000; position: relative;", #class = "report-grid", report_guid = guid })
)
When I tried to double click the word 'datasource' it only highlighted half of the word, so I re-typed it and added a model.Id to the model definition and it worked.
I have no idea what happened here.

Update is not working in my mvc project

hello everyone i am tring to update the database. but update is not working in my project. i used a single action to create and update.And i am using kendo grid control in this project and edit the popup template. so please check this and suggest me something why update is not working.
this is my code.
public class ImageController : Controller
{
ShoppingContext db = new ShoppingContext();
string imagename;
string path;
// GET: /Image/
public ActionResult Index()
{
return View();
}
public JsonResult GetData([DataSourceRequest] DataSourceRequest request)
{
var list = db.ImageModels.ToList();
return Json(list.ToDataSourceResult(request));
}
public ActionResult Create(IEnumerable<HttpPostedFileBase> files, ImageModel imageModel)
{
foreach (var image in files)
{
imagename = Path.GetFileName(image.FileName);
path = "~/Images/" + imagename;
var projectpath = Path.Combine(Server.MapPath("~/Images"), imagename);
image.SaveAs(projectpath);
}
var id = imageModel.Imageid;
if (id > 0)
{
imageModel.ImageName = imagename;
imageModel.ImageUrl = path;
db.SaveChanges();
}
else
{
imageModel.ImageName = imagename;
imageModel.ImageUrl = path;
db.ImageModels.Add(imageModel);
db.SaveChanges();
}
return RedirectToAction("Index");
}
}
My view
#(Html.Kendo().Grid<TelerikMVCImageProject.Models.ImageModel>()
.Name("grdImage")
.DataSource(datasource => datasource
.Ajax()
.Model(model => model.Id(p=>p.Imageid))
.Create(create => create.Action("Create", "Image"))
.Update(update => update.Action("Create", "Image"))
.Destroy(delete => delete.Action("Delete", "Image"))
.Read(read => read.Action("GetData", "Image"))
.ServerOperation(false)
.Model(model =>
{
model.Field(p => p.Imageid).Editable(true);
model.Id(p => p.Imageid);
// model.Field(p => p.isenabled).DefaultValue(true);
})
)
.Columns(columns =>
{
//columns.Bound(c => c.IMAGESIZE_ID).ClientTemplate("<input type='checkbox' value #=IMAGESIZE_ID# />").Width(50);
columns.Bound(c => c.ProductName).Width(140).Title("Product Name");
columns.Bound(c => c.ProductDesc).Title("Product Desc");
columns.Bound(c => c.ImageName).Title("Image Name");
columns.Bound(c => c.ImageUrl).Title("Image Url");
columns.Command(command =>
{
command.Edit();
command.Destroy();
//command.Custom("Edit").Action("Update", "Imagetest").Text("Edit");
});
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("ImageModel"))
.HtmlAttributes(new { style = "height: 580px;" })
.Scrollable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5)
)
)
My Editor Templates
#model TelerikMVCImageProject.Models.ImageModel
<style>
.k-state-default {
visibility:hidden;
}
</style>
<script>
function onSelect(e) {
alert("Select");
$demo = $("#files").val();
var filename = $demo.substr(12);
var path = "~/Images/" + filename;
$("#divimage").append('<img src = "#Url.Content("~/Images/")' + filename + '">');
alert(path);
}
function onRemove(e) {
alert("Remove");
$("#divimage").empty();
}
</script>
<form method="post" action="#Url.Action("Create")">
<table>
<tr>
#Html.HiddenFor(m=>m.Imageid)
</tr>
<tr>
<td>#Html.Label("Product Name")</td>
<td>#Html.TextBoxFor(m=>m.ProductName)</td>
</tr>
<tr>
<td>#Html.Label("Product Desc")</td>
<td>#Html.TextBoxFor(m=>m.ProductDesc)</td>
</tr>
<tr>
<td>#Html.Label("Image Desc")</td>
<td>#(Html.Kendo().Upload()
.Name("files")
.Multiple(false)
.Messages(msg => msg.Select("Browser"))
//.Async(a=>a.AutoUpload(false).Save("Save","Imagetest"))
.Events(e=>e.Select("onSelect").Remove("onRemove"))
)</td>
</tr>
<tr>
<td></td>
<td><div id="divimage" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save" /></td>
</tr>
</table>
</form>
This is because you are receiving the model from the user and not "attaching" it to the EF db context. You need to attach it before saving changes.
Try the following (in ImageController):
if (id > 0)
{
db.ImageModels.Attach(imageModel);
imageModel.ImageName = imagename;
imageModel.ImageUrl = path;
db.SaveChanges();
}

Kendo MVC Wrapper - Custom Editor if grid

I'm trying to get a custom popup editor working in our Grid using MVC wrappers.
The MVC wrapper is
Html.Kendo().Grid(#Model.ReferralCommentsViewModel.ReferralComments)
.Name("gridComment")
.Columns(columns =>
{
columns.Bound(p => p.CommentValue).Title("Comment").Encoded(false).Width(450);
columns.Bound(p => p.CreatedBy).Title("Created By").ClientTemplate("#= kendo.toString(CreatedBy) #").Width(100);
columns.Bound(p => p.CreatedDate).Title("Create Date").ClientTemplate("#= kendo.toString(CreatedDate, \"MM/dd/yyyy\") #").Width(70);
columns.Command(command => { command.Edit().Text(" "); }).Title("Edit").Width(20);
columns.Command(command => { command.Destroy().Text(" "); }).Title("Delete").Width(20);
})
.ToolBar(toolbar => toolbar.Create().Text("Add new Comment"))
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("popupEditorTemplate").Window(w=>w.Title("Add/Edit Comment")))
.Resizable(resize => resize.Columns(true))
.Sortable()
.Selectable()
.HtmlAttributes(new { style = "height:165px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.AutoSync(false)
.Batch(true)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(p => p.CommentID))
.Create(update => update.Action("EditingPopup_Create", "Referral"))
.Read(read => read.Action("EditingPopup_Read", "Referral"))
.Update(update => update.Action("EditingPopup_Update", "Referral"))
.Destroy(update => update.Action("EditingPopup_Destroy", "Referral"))
)
The editor template is -
<script id="popupEditorTemplate" type="text/x-kendo-template">
<label for="Created Date">Created Date:</label><Input data-bind= "value: CreatedDate" readonly="true" />
<label for="Created By">CreatedBy:</label><Input data-bind= "value:CreatedBy" readonly="true" />
<label for="Created By">Comments:</label>
<textarea data-role="editor"
data-bind="value: CommentValue"
style="width: 280px"></textarea>
</script>
No matter what options I use, I cannot get the custom edit template to display in the popup. Only the default popup is displayed. Is there something obvious missing?
Project - VS2012, MVC4
TemplateName should specify the name of the view which is a cshtml in the EditorsTemplate folders which MVC searches automatically.
It should not be the name of a html element which holds a Kendo template (like you did). More info about MVC EditorTemplates can be found here.

Hierarchy Kendo Grid is not working properly in Mvc 4

I have created a kendo hierarchy grid in mvc 4. On execution of the grid, the hierarchy grid is expand automatically for the first row, but when i expand the another row then the new hierarchy grid comes up empty while the data of the earlier hierarchy grid (which comes up by default) was changed.
1. How can i make it to show data in the hierarchy grid for the
particular row only not in the default opened grid?
2. Also how can i prevent the default expansion of the row.
View:
#(Html.Kendo().Grid<KendoUI.Models.EmployeeViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.name).Title("Name");
columns.Bound(p => p.gender).Title("Gender");
columns.Bound(p => p.designation).Title("Designation").Width("300px");
columns.Bound(p => p.department).Title("Department").Width("300px");
})
.ClientDetailTemplateId("template")
.HtmlAttributes(new { style = "height:430px;" })
.Pageable()
.Navigatable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource // Configure the grid data source
.Ajax()
.Model(model =>
{
model.Id(x => x.id);
})
.Read(read => read.Action("Employee_Read", "Home")) // Set the action method which will return the data in JSON format
)
.Events(events => events.DataBound("dataBound"))
)
<script id="template" type="text/kendo-tmpl">
#(Html.Kendo().Grid<KendoUI.Models.EmployeeViewModel>()
.Name("grid_#id#")
.Columns(columns =>
{
columns.Bound(p => p.id).Width(70);
columns.Bound(p => p.name).Width(110);
columns.Bound(p => p.gender).Width(110);
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(5)
.Read(read => read.Action("Department_Read", "Home", new { employeeID = "#=id#" }))
)
.Pageable()
.Sortable()
.ToClientTemplate()
)
</script>
<script>
function dataBound() {
this.expandRow(this.tbody.find("tr.k-master-row").first());
}
</script>
Controller:
public ActionResult Employee_Read([DataSourceRequest]DataSourceRequest request)
{
//code for grid
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult Department_Read(Int32 employeeID, [DataSourceRequest]DataSourceRequest request)
{
// Code for hierarchy grid detail
return Json(result, JsonRequestBehavior.AllowGet);
}
You made a mistake in your detail Template
you should use .Name("grid_#=id#") instead of .Name("grid_#id#") the '=' matters.Causing all of your hierarchy-grids to share the same id so only the first grid is refreshed everytime.
your databound() function is causing the expansion of the first by default (and everytime the grid is bound to it datasource.)

Resources