Adding parent and child to Kendo UI controller using MVC 5 - model-view-controller

I am using MVC 5 with Kendo UI(Latest Version) and SQL Server 2014, and I want to add a treeview controller that will display parent items and child items when users click on the parent item. I have two classes:
1.Category
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProductTreeView.Models
{
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
}
2.Product
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProductTreeView.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Category Category { get; set; }
public int CategoryId { get; set; }
}
}
My controller action looks like this:
public ActionResult Products(int? id)
{
var model = db.Categories
.Select(p => new {
id = p.Id,
Name = p.Name,
hasChildren = p.Products.Any()
});
return this.Json(model, JsonRequestBehavior.AllowGet);
}
And the HTML looks like this:
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div class="row">
<div class="col-md-3">
<label class="k-label-top">TreeView</label>
#(Html.Kendo().TreeView().Name("treeview")
.DataSource(datasource => datasource
.Read(read => read.Action("Products", "Categories"))
).DataTextField("Name")
)
</div>
</div>
The result is parent items within parent items, looping.
Results

That is a self referencing example you might use for employees/managers. You need the more classical way where you provide the child products in a collection.
public ActionResult Products(int? id)
{
var model = db.Categories
.Select(p => new {
id = p.Id,
Name = p.Name,
hasChildren = p.Products.Any(),
Children = p.Products
});
return this.Json(model, JsonRequestBehavior.AllowGet);
}
Then something like:
#(Html.Kendo().TreeView().Name("treeview")
.DataSource(d => d
.Model(m => m
.Id("Id")
.HasChildren("hasChildren")
.Children("Children"))
.Read(r => r.Action("Products", "Categories")))
.DataTextField("Name"))
http://demos.telerik.com/kendo-ui/treeview/local-data-binding

Related

Pass Telerik:Grid-data over form-action (MVC)

I have a very special problem and wasn't yet able to find anything to help me solving it.
I have a form which has a bunch of textboxes, dropdownlists and such which are posted back through the model attached in the view. However I also have a Grid which is dynamically populated through one of the DropDownLists. I want to parse the whole grid back to the forms-controller, but I have no clue how to do that.
An ajax-post doesn't work, because I have no access to the actual model. The only thing I could do is post the controls-values itself, but that approach is somewhat messy.
The model itself has a variable "Mappings" which is of the Type IEnumerable. This is the type I also bind to the grid. So there should be a way to somehow add the mappings inside of the grid to the model. I thought it might work automatically if I name the grid like the name of the property inside of the main model ("Mappings"), but that didn't work. So I am yet again back to square one.
Maybe you guys have an idea how to solve my Problem as I am somewhat out of ideas.
View:
#using (Html.BeginForm("Save", "Profile", FormMethod.Post, new { Id = "addProfileForm", novalidate = "false" }))
{
<ul id="progressbar">
<li class="active">Grundeinstellungen</li>
<li>CRM-Einstellungen</li>
<li>Mapping anlegen</li>
</ul>
<fieldset>
<h2 class="fs-title">Grundinformationen</h2>
#Html.LabelFor(model => model.Name, new { #class = "label req" })
#Html.TextBoxFor(model => model.Name, new { #class = "input" })
#Html.LabelFor(model => model.Description, new { #class = "label" })
#Html.TextAreaFor(model => model.Description, new { #class = "input", rows = "3", cols = "25" })
#Html.LabelFor(model => model.UserGroupId, new { #class = "label req" })
#(Html.Kendo().DropDownListFor(model => model.UserGroupId)
.OptionLabel("Bitte auswählen... ")
.BindTo(Model.UserGroupList)
)
<input type="button" name="next" class="next action-button" value="Weiter" style="display:block"/>
</fieldset>
<fieldset>
<h2 class="fs-title">CRM-Einstellungen</h2>
#Html.LabelFor(model => model.OrdnungsbegriffTypeId, new { #class = "label req" })
#(Html.Kendo().DropDownListFor(model => model.OrdnungsbegriffTypeId)
.OptionLabel("Bitte auswählen...")
.BindTo(Model.OrdnungsbegriffTypeList)
)
#Html.LabelFor(model => model.CrmTypeId, new { #class = "label req" })
#(Html.Kendo().DropDownListFor(model => Model.CrmTypeId)
.Name("CrmTypeId")
.OptionLabel("Bitte auswählen...")
.BindTo(Model.CrmTypeList)
.Events(e =>
e.Select("onCrmTypeSelect"))
)
<br />
<input type="button" name="previous" class="previous action-button" value="Zurueck" />
<input type="button" name="next" class="next action-button" value="Weiter" />
</fieldset>
<fieldset>
<h2 class="fs-title">Mapping anlegen</h2>
#(Html.Kendo().Upload()
.Name("upMappingFile")
.Multiple(false)
.ShowFileList(true)
.TemplateId("fuCsvTemplate")
.Async(a => a
.AutoUpload(true)
.Save("SaveFile", "Mapping")
.Remove("RemoveFile", "Mapping")
)
.Enable(false)
.Events(e => e
.Success("onSuccess"))
.Messages(m => m
.Select("Durchsuchen...")
.HeaderStatusUploading("Uploading...")
.HeaderStatusUploaded("Fertig"))
)
<div id="gridContainer">
</div>
<div id="appendTo" class="k-block"></div>
<input type="button" name="previous" class="previous action-button" value="Zurueck" />
<input type="submit" name="submit" class="submit action-button" value="Speichern"/>
</fieldset>
#Html.Kendo().Notification().Name("crmTypeNotification")
}
Ajax-Post for dynamically creating the grid:
function onSuccess(e) {
var gridNotification = $("#gridNotification").data("kendoNotification");
var crmType = $("#CrmTypeId").data("kendoDropDownList");
var csvHeadRow = e.response.csvHeadRow
var url = '#Url.Action(MVC.Mapping.ReturnMappingGrid())';
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({ csvHead: csvHeadRow, crmType: crmType.text() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#gridContainer').html(data);
gridNotification.show("Die Auswahl der jeweiligen Eigenschaft erfolgt durch Klicken des jeweiligen Eigenschaft-Felds!")
var container = $(gridNotification.options.appendTo);
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
debugger;
console.log(xmlHttpRequest.responseText);
console.log(textStatus);
console.log(errorThrown);
},
async: false
});
}
Partial View Grid:
#(Html.Kendo().Grid<DAKCrmImportModel.Model.Entities.Base.CrmMapping>().Name("Mappings").BindTo(Model)
.Columns(c =>
{
c.Bound(m => m.CsvColumn).Title("Spalte").Width(300);
c.Bound(m => m.CrmProperty).EditorTemplateName("PropertyId");
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Model(m =>
{
m.Id(ma => ma.Id);
m.Field(ma => ma.Id).Editable(false);
})
)
)
CrmProfile-model:
public class CrmProfile
{
public CrmProfile()
{
this.Mappings = new HashSet<CrmMapping>();
this.Jobs = new HashSet<CrmJob>();
}
[Column(Order = 1)]
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Bezeichnung")]
public string Name { get; set; }
[Display(Name = "Beschreibung")]
public string Description { get; set; }
[Required]
public string CreatedBy { get; set; }
[Column(Order = 2)]
[ForeignKey("UserGroup")]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
[Required]
[Display(Name = "Usergruppe")]
public int UserGroupId { get; set; }
public UserGroup UserGroup { get; set; }
[Column(Order = 3)]
[ForeignKey("CrmType")]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
[Required]
[Display(Name = "Einspielungstyp")]
public int CrmTypeId { get; set; }
public CrmImportType CrmType { get; set; }
[Column(Order = 4)]
[ForeignKey("OrdnungsbegriffType")]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
[Required]
[Display(Name = "Ordnungsbegrifftyp")]
public int OrdnungsbegriffTypeId { get; set; }
public OrdnungsbegriffType OrdnungsbegriffType { get; set; }
public byte[] SourceFile { get; set; }
public string SourceFileName { get; set; }
public string[] SourceFileHeadRow { get; set; }
[Required]
public DateTime CreatedAt { get; set; }
public string LastUpdatedBy { get; set; }
public DateTime? LastUpdatedAt { get; set; }
public DateTime? LastUsedAt { get; set; }
public ICollection<CrmMapping> Mappings { get; set; }
public ICollection<CrmJob> Jobs { get; set; }
[NotMapped]
public IEnumerable<SelectListItem> UserGroupList { get; set; }
[NotMapped]
public IEnumerable<SelectListItem> CrmTypeList { get; set; }
[NotMapped]
public IEnumerable<SelectListItem> OrdnungsbegriffTypeList { get; set; }
}
CrmMapping-model:
public class CrmMapping
{
[Key]
[Column(Order = 0)]
public int Id { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
[ForeignKey("Profile")]
public int ProfileId { get; set; }
public CrmProfile Profile { get; set; }
[Required]
public string CrmProperty { get; set;}
[Required]
public string CsvColumn { get; set; }
[Required]
public int CsvIndex { get; set; }
[UIHint("PropertyId")]
[NotMapped]
public int PropertyId { get; set; }
[NotMapped]
public IEnumerable<CrmProperty> CrmProperties { get; set; }
}
[UPDATE]
I want to post the grid-data back with ajax, but I don't seem to get the right datatype on serverside.
function postProfileData() {
var url = '/Profile/Save';
$.ajax({
type: "POST",
url: url,
data: $("#addProfileForm").serialize() + "&Mappings=" + getMappings(),
success: function (data) {
debugger;
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
debugger;
console.log(xmlHttpRequest.responseText);
console.log(textStatus);
console.log(errorThrown);
},
async: false
});
}
function getMappings() {
var grid = $("#Mappings").data("kendoGrid");
debugger;
return grid._data;
}
[HttpPost]
public virtual ActionResult Save(CrmProfile crmProfile, List<CrmMapping> Mappings)
{
using (DAKCrmImportContext db = new DAKCrmImportContext())
{
crmProfile.CreatedAt = DateTime.Now;
crmProfile.CreatedBy = System.Web.HttpContext.Current.User.Identity.Name.Split('\\')[1];
try
{
db.CrmProfiles.Add(crmProfile);
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
var vals = e.EntityValidationErrors;
throw;
}
}
return RedirectToAction("Add", "Mapping", crmProfile);
}
[UPDATE2] So the problem is likely that JavaScript doesn't like my Listtype (CrmMapping) and doesn't know what to do with it. I'm not quite sure why, but I think its's because its structure doesn't fit the normal id:value pair. Maybe the problem is that Id is 0 in all ListItems and I'll have to fill it manually, but CrmMapping is actually a model-class so I'd have to set it back to 0 eventually so I'd probably have to create a ViewModel just to parse the grid-data back.
public class CrmMapping
{
[Key]
[Column(Order = 0)]
public int Id { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
[ForeignKey("Profile")]
public int ProfileId { get; set; }
public CrmProfile Profile { get; set; }
[Required]
public string CrmProperty { get; set;}
[Required]
public string CsvColumn { get; set; }
[Required]
public int CsvIndex { get; set; }
[UIHint("PropertyId")]
[NotMapped]
public int PropertyId { get; set; }
[NotMapped]
public IEnumerable<CrmProperty> CrmProperties { get; set; }
}
Since you're creating the grid from the #model instead of using ajax calls for the datasource.Read, you could just create hidden inputs using a for loop, and as long as they're in the form tag they would post back.
Something like
#(Html.Kendo().Grid<DAKCrmImportModel.Model.Entities.Base.CrmMapping>().Name("Mappings").BindTo(Model)
.Columns(c =>
{
c.Bound(m => m.CsvColumn).Title("Spalte").Width(300);
c.Bound(m => m.CrmProperty).EditorTemplateName("PropertyId");
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Model(m =>
{
m.Id(ma => ma.Id);
m.Field(ma => ma.Id).Editable(false);
})
)
)
#for (int i = 0; i < Model.Count; i++)
{
#Html.Hidden("Mappings[" + i.ToString() + "].Id", Model[i].Id)
#Html.Hidden("Mappings[" + i.ToString() + "].CsvColumn", Model[i].CsvColumn)
#Html.Hidden("Mappings[" + i.ToString() + "].CrmProperty", Model[i].CrmProperty)
}
If you edit any of the columns, the new values won't get posted back using this method so you should probably wire up the ajax datasource events to Read, Create, Edit and Delete if you want to be able to maintain the grid data correctly
Ok, after trying a bunch of things I finally found a solution. To do this I need a javscript-expension:
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
This is needed to serialize the form as an object instead of posting the form itself.
The next thing we have to do is create a ViewModel which has properties for the model of the form we want to submit/post and the additional data we want to get into the controller-action.
using DAKCrmImportModel.Model.Entities.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DAKCrmImport.Models
{
public class CrmProfileAddVM
{
public CrmProfile Profile { get; set; }
public CrmMapping[] Mappings { get; set; }
}
}
We have to declare CrmMapping as Array here, because thats the datatype the Telerik-grid uses.
Now let's do the ajax-function which contains our ViewModel with the form-data (Profile) and the grid._data (Mappings).
function postProfileData() {
var url = '#Url.Action(MVC.Profile.Save())';
$.ajax({
type: "POST",
url: url,
//.serialize()
//data: $("#addProfileForm").serialize(), "crmMappingList": getMappings(),
contentType: 'application/json',
data: JSON.stringify({
Profile: $("form#addProfileForm").serializeObject(),
Mappings: getMappings()
}),
//data: { Mappings: getMappings() },
success: function (data) {
debugger;
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
debugger;
console.log(xmlHttpRequest.responseText);
console.log(textStatus);
console.log(errorThrown);
},
async: false
});
}
function getMappings() {
var grid = $("#Mappings").data("kendoGrid");
return grid._data;
}
Finally the last thing we have to do is change the controller-Action Parameter so that we have access to the instance of our ViewModel.
[HttpPost]
public virtual ActionResult Save(CrmProfileAddVM model)
{
using (DAKCrmImportContext db = new DAKCrmImportContext())
{
//crmProfile.CreatedAt = DateTime.Now;
//crmProfile.CreatedBy = System.Web.HttpContext.Current.User.Identity.Name.Split('\\')[1];
//try
//{
// db.CrmProfiles.Add(crmProfile);
// db.SaveChanges();
//}
//catch (DbEntityValidationException e)
//{
// var vals = e.EntityValidationErrors;
// throw;
//}
}
return RedirectToAction("Add", "Mapping", null);
}

Multiple ViewModels in View

I'm looking to display two Telerik Kendo grids with different information(models) in one view and I'm not sure how to do it.
Model:
using System.Collections.Generic;
namespace KendoUIMvcApplication1.Models
{
public class Car
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Truck
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Vehicles
{
public IEnumerable<Car> CarCol { get; set; }
public IEnumerable<Truck> TruckCol { get; set; }
}
}
Controller (Creating some test objects):
using System.Collections.Generic;
using System.Web.Mvc;
using KendoUIMvcApplication1.Models;
namespace KendoUIMvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var carList = new List<Car>();
var truckList = new List<Truck>();
var vehCol = new Vehicles();
var car1 = new Car
{
Id = 1,
Name = "Passat"
};
var car2 = new Car
{
Id = 2,
Name = "Passat"
};
carList.Add(car1);
carList.Add(car2);
var truck1 = new Truck
{
Id = 1,
Name = "S10"
};
var truck2 = new Truck
{
Id = 1,
Name = "Blazer"
};
truckList.Add(truck1);
truckList.Add(truck2);
vehCol.CarCol = carList;
vehCol.TruckCol = truckList;
return View(vehCol);
}
}
}
View (Here I'm trying to display the two grids. The first one for cars and the second one for trucks):
#using KendoUIMvcApplication1.Models
#model IEnumerable<Vehicles>
#*// Car Grid*#
#(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns => {
columns.Bound(c => c.Id);
columns.Bound(c => c.Name);
})
)
<div></div>
#*// Truck Grid*#
#(Html.Kendo().Grid(Model))
.Name("Grid")
.Columns(columns => {
columns.Bound(t => t.Id);
columns.Bound(t => t.Name);
})
)
Your model should be of type Vehicles:
#model Vehicles
Then you can access the two collections:
#Html.Kendo().Grid(Model.CarCol)
...
and
#Html.Kendo().Grid(Model.TruckCol)
...

MVC3 Can't get model back to the controller

I have the following ViewModel
public class RecommendationModel
{
public List<CheckBoxItem> CheckBoxList { get; set; }
}
public class CheckBoxItem
{
public string Text { get; set; }
public bool Checked { get; set; }
public string Link { get; set; }
}
With the following View
model Sem_App.Models.RecommendationModel
#using (Html.BeginForm())
{
for (int i = 0; i < Model.CheckBoxList.Count(); i++) {
#Html.CheckBoxFor(m => m.CheckBoxList[i].Checked)
#Html.DisplayFor(m => m.CheckBoxList[i].Text)
}
<input type="submit" value="Add To Playlist" />
}
With the following controller actions
//get
public ActionResult Recommendation()
{
RecommendationModel model = new RecommendationModel();
model.CheckBoxList = new List<CheckBoxItem>();
return PartialView(model);
}
//post
[HttpPost]
public ActionResult Recommendation(RecommendationModel model)
{
foreach (var item in model.CheckBoxList)
{
if (item.Checked)
{
// do something with item.Text
}
}
}
Problem is whenever I select some items and press the submit button the model returned has CheckBoxList as empty. How can I change my view to return the list of CheckBoxList? Trying
#Html.HiddenFor(m => m.checkBoxList) did not work for me
I think you nee something like this
#using (Html.BeginForm())
{
for (int i = 0; i < Model.CheckBoxList.Count(); i++) {
#Html.CheckBoxFor("Model.CheckBoxItem[" + i + "].Checked" , m => m.CheckBoxList[i].Checked)
#Html.DisplayFor("Model.CheckBoxItem[" + i + "].Text",m => m.CheckBoxList[i].Text)
}
Try adding the link as a hidden field: #Html.HiddenFor(m => m.CheckBoxList[i].Link )
Check how the checkbox input name is in the rendered html and also check the form action is sending to the corrent controller/action and the method is post
it should be something very simple.. create the action param as array with the same name of the "name" attribute form check box input
something like this
[HttpPost]
public ActionResult Delete(int[] checkName)
{
}

MVC3 dropdown list that displays mutliple properties per item

I want to have a dropdownlist in my view that displays a patient's ID, First Name, and Last Name. With the code below, it displays each patient's First Name. How can I pass all three properties into the viewbag and have them display in the dropdownlist?
Controller
public ActionResult Create()
{ViewBag.Patient_ID = new SelectList(db.Patients, "Patient_ID", "First_Name");
return View();
}
View
<div class="editor-field">
#Html.DropDownList("Patient_ID", String.Empty)
#Html.ValidationMessageFor(model => model.Patient_ID)
</div>
Thanks.
Ok, I have edited my code as follows, and I receive the error "There is no ViewData item of type 'IEnumerable' that has the key 'SelectedPatientId'."
Controller
public ActionResult Create()
{
var model = new MyViewModel();
{
var Patients = db.Patients.ToList().Select(p => new SelectListItem
{
Value = p.Patient_ID.ToString(),
Text = string.Format("{0}-{1}-{2}", p.Patient_ID, p.First_Name, p.Last_Name)
});
var Prescribers = db.Prescribers.ToList().Select(p => new SelectListItem
{
Value = p.DEA_Number.ToString(),
Text = string.Format("{0}-{1}-{2}", p.DEA_Number, p.First_Name, p.Last_Name)
});
var Drugs = db.Drugs.ToList().Select(p => new SelectListItem
{
Value = p.NDC.ToString(),
Text = string.Format("{0}-{1}-{2}", p.NDC, p.Name, p.Price)
});
};
return View(model);
}
View Model
public class MyViewModel
{
[Required]
public int? SelectedPatientId { get; set; }
public IEnumerable<SelectListItem> Patients { get; set; }
[Required]
public int? SelectedPrescriber { get; set; }
public IEnumerable<SelectListItem> Prescribers { get; set; }
[Required]
public int? SelectedDrug { get; set; }
public IEnumerable<SelectListItem> Drugs { get; set; }
}
View
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
#Html.DropDownListFor(
x => x.SelectedPatientId,
Model.Patients,
"-- Select patient ---"
)
#Html.ValidationMessageFor(x => x.SelectedPatientId)
<button type="submit">OK</button>
#Html.DropDownListFor(
x => x.SelectedPrescriber,
Model.Patients,
"-- Select prescriber ---"
)
#Html.ValidationMessageFor(x => x.SelectedPrescriber)
<button type="submit">OK</button>
}
I would recommend you not to use any ViewBag at all and define a view model:
public class MyViewModel
{
[Required]
public int? SelectedPatientId { get; set; }
public IEnumerable<SelectListItem> Patients { get; set; }
}
and then have your controller action fill and pass this view model to the view:
public ActionResult Create()
{
var model = new MyViewModel
{
Patients = db.Patients.ToList().Select(p => new SelectListItem
{
Value = p.Patient_ID.ToString(),
Text = string.Format("{0}-{1}-{2}", p.Patient_ID, p.First_Name, p.Last_Name)
});
};
return View(model);
}
and finally in your strongly typed view display the dropdown list:
#model MyViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(
x => x.SelectedPatientId,
Model.Patients,
"-- Select patient ---"
)
#Html.ValidationMessageFor(x => x.SelectedPatientId)
<button type="submit">OK</button>
}
Easy way to accomplish that is just creating additional property on your model either by modifying model class or adding/modifying a partial class
[NotMapped]
public string DisplayFormat
{
get
{
return string.Format("{0}-{1}-{2}", Patient_ID, First_Name, Last_Name);
}
}

Nested EditorTemplates in Telerik MVC Grid Edit Popup Window Not Displaying in Custom Edit Template

I have a grid using AJAX DATABINDING.
When I issue a POPUP EDITING command with TEMPLATENAME SPECIFIED my NESTED EDITOR TEMPLATES are not populating.
My Models
namespace eGate.BackOffice.WebClient.Model
{
public class TemplateTesterModel
{
public int TemplateModelId { get; set; }
public string TemplateModelName { get; set; }
public List<UserRole> UserRoles { get; set; }
}
}
{
public class TemplateTesterModels : List<TemplateTesterModel>
{
}
}
My View
#model eGate.BackOffice.WebClient.Model.TemplateTesterModels
#Html.EditorFor(m=>m)
#( Html.Telerik().Grid<eGate.BackOffice.WebClient.Model.TemplateTesterModel>()
.Name("Grid")
.DataKeys(keys => { keys.Add(m=>m.TemplateModelId); })
.Columns(columns =>
{
columns.Bound(o => o.TemplateModelId);
columns.Bound(o => o.TemplateModelName).Width(200);
columns.Bound(o => o.UserRoles).ClientTemplate(
"<# for (var i = 0; i < UserRoles.length; i++) {" +
"#> <#= UserRoles[i].RoleName #> <#" +
"} #>")
;
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.Text);
}).Width(180).Title("Commands");
})
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("_SelectAjaxEditing", "TemplateTester")
.Insert("_InsertAjaxEditing", "Grid")
.Update("_SaveAjaxEditing", "TemplateTester")
.Delete("_DeleteAjaxEditing", "TemplateTester")
)
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("TemplateTesterModel"))
)
My Controller
namespace eGate.BackOffice.WebClient.Controllers
{
public class TemplateTesterController : Controller
{
public ActionResult Index()
{
return View(GetTemplateTesters());
//return View(new GridModel(GetTemplateTesters()));
}
private TemplateTesterModels GetTemplateTesters() {
TemplateTesterModels returnme = new TemplateTesterModels();
returnme.Add(new TemplateTesterModel());
returnme[0].TemplateModelId = 0;
returnme[0].TemplateModelName = "Template Tester 0";
returnme[0].UserRoles = new List<UserRole>();
returnme[0].UserRoles.Add(new UserRole() { RoleName = "Role1", IsChecked = true, Description = "Role for 1" });
returnme[0].UserRoles.Add(new UserRole() { RoleName = "Role2", IsChecked = false, Description = "Role for 2" });
returnme[0].UserRoles.Add(new UserRole() { RoleName = "Role3", IsChecked = false, Description = "Role for 3" });
return returnme;
}
[GridAction]
public ActionResult _SelectAjaxEditing()
{
return View(new GridModel(GetTemplateTesters()));
}
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult _SaveAjaxEditing(int id)
{
return View(new GridModel(GetTemplateTesters()));
}
[GridAction]
public ActionResult _InsertAjaxEditing(){
return View(new GridModel(GetTemplateTesters()));
}
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult _DeleteAjaxEditing(int id)
{
return View(new GridModel(GetTemplateTesters()));
}
}
}
My EditorTemplates
Shared/EditorTemplates/TemplateTesterModel.cshtml
#model eGate.BackOffice.WebClient.Model.TemplateTesterModel
<div>TemplateTesterModel Editor</div>
<div>#Html.EditorFor(m=>m.TemplateModelId)</div>
<div>#Html.EditorFor(m=>m.TemplateModelName)</div>
<div>Roles</div>
<div>#Html.EditorFor(m=>m.UserRoles)</div>
Shared/EditorTemplates/UserRole.cshtml
#model eGate.BackOffice.WebClient.Model.UserRole
<div>
I can has user role?
#Html.CheckBoxFor(m=>m.IsChecked)
</div>
This renders out as such:
As you can see the #Html.EditFor statements that precede the grid filter down through to the userrole EditorTemplate as expected. Additionally we can see that role data is in the grid because it is showing up in the role column.
But click the edit window and this is the result:
As you can see the UserRoles template is not populating with the roles on the UserRoles property of the TemplateTesterModel we're editing.
Am I missing something? Why is the .UserRoles property not populating in the telerik grid pop-up window?
This could be a "by design" decision of ASP.NET MVC. It does not automatically render display and editor templates for nested complex objects. I even have a blog post discussing this.
Long story short you need to create a custom editor template for the parent model.

Resources