Here is my code. I'm trying to use the Grid for the first time in my own application.
public class CustomerViewModel
{
[ScaffoldColumn(false)]
public int CustomerID { get; set; }
[DisplayName("First name")]
public string FirstName { get; set; }
[DisplayName("Last name")]
public string LastName { get; set; }
public string Phone { get; set; }
public string Company { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
[DisplayName("State/Province")]
public string StateProvince { get; set; }
[DisplayName("Zip/Postal code")]
public string ZipPostalCode { get; set; }
[UIHint("ClientCountry")]
public CountryViewModel Country { get; set; }
[DisplayName("Country")]
public string CountryID { get; set; }
[DisplayName("VAT number")]
public string VatNumber { get; set; }
[DisplayName("Codice destinatario SDI")]
public string DestCode { get; set; }
public string Notes { get; set; }
[ScaffoldColumn(false)]
public int OrderCount { get; set; }
}
public class CountryViewModel
{
public string CountryID { get; set; }
public string CountryName { get; set; }
}
public class CustomerService : IDisposable
{
private static bool UpdateDatabase = false;
private devDeptMvcContext entities;
public CustomerService(devDeptMvcContext entities)
{
this.entities = entities;
}
public IList<
CustomerViewModel
> GetAll()
{
var result = HttpContext.Current.Session["Customers"] as IList<
CustomerViewModel
>;
if (result == null || UpdateDatabase)
{
result = entities.Customers.Select(customer => new CustomerViewModel
{
CustomerID = customer.customerID,
FirstName = customer.firstName,
LastName = customer.lastName,
Phone = customer.phone,
Company = customer.company,
Address1 = customer.address1,
Address2 = customer.address2,
City = customer.city,
StateProvince = customer.stateProvince,
ZipPostalCode = customer.zipPostalCode,
CountryID = customer.countryID,
Country = new CountryViewModel()
{
CountryID = customer.Country.countryID,
CountryName = customer.Country.countryName
},
VatNumber = customer.vatNumber,
DestCode = customer.destCode,
Notes = customer.notes,
OrderCount = customer.Orders.Count
}).ToList();
HttpContext.Current.Session["Customers"] = result;
}
return result;
}
public IEnumerable<
CustomerViewModel
> Read()
{
return GetAll();
}
public void Create(CustomerViewModel customer)
{
if (!UpdateDatabase)
{
/*var first = GetAll().OrderByDescending(e => e.CustomerID).FirstOrDefault();
var id = (first != null) ? first.CustomerID : 0;
customer.CustomerID = id + 1;
if (customer.CustomerID == null)
{
customer.CustomerID = 1;
}*/
if (customer.Country == null)
{
customer.Country = new CountryViewModel() {CountryID = "ITA", CountryName = "Italy"};
}
GetAll().Insert(0, customer);
}
else
{
var entity = new Customer();
entity.firstName = customer.FirstName;
entity.lastName = customer.LastName;
entity.company = customer.Company;
entity.address1 = customer.Address1;
entity.address2 = customer.Address2;
entity.city = customer.City;
entity.stateProvince = customer.StateProvince;
entity.zipPostalCode = customer.ZipPostalCode;
entity.vatNumber = customer.VatNumber;
entity.destCode = customer.DestCode;
entity.notes = customer.Notes;
entity.countryID = customer.CountryID;
/*if (entity.countryID == null)
{
entity.countryID = "ITA";
}*/
if (customer.Country != null)
{
entity.countryID = customer.Country.CountryID;
}
entities.Customers.Add(entity);
entities.SaveChanges();
customer.CustomerID = entity.customerID;
}
}
public void Update(CustomerViewModel customer)
{
if (!UpdateDatabase)
{
var target = One(e => e.CustomerID == customer.CustomerID);
if (target != null)
{
target.FirstName = customer.FirstName;
target.LastName = customer.LastName;
target.Phone = customer.Phone;
target.Company = customer.Company;
target.Address1 = customer.Address1;
target.Address2 = customer.Address2;
target.City = customer.City;
target.StateProvince = customer.StateProvince;
target.ZipPostalCode = customer.ZipPostalCode;
target.VatNumber = customer.VatNumber;
target.DestCode = customer.DestCode;
target.Notes = customer.Notes;
/*if (customer.Country != null)
{*/
customer.CountryID = customer.Country.CountryID;
/*}
else
{
customer.Country = new CountryViewModel()
{
CountryID = customer.CountryID,
CountryName = entities.Countries.Where(s => s.countryID == customer.CountryID)
.Select(s => s.countryName).First()
};
}*/
target.CountryID = customer.CountryID;
target.Country = customer.Country;
}
}
else
{
var entity = new Customer();
entity.customerID = customer.CustomerID;
entity.firstName = customer.FirstName;
entity.lastName = customer.LastName;
entity.company = customer.Company;
entity.address1 = customer.Address1;
entity.address2 = customer.Address2;
entity.city = customer.Address2;
entity.countryID = customer.CountryID;
/*if (customer.Country != null)
{*/
entity.countryID = customer.Country.CountryID;
/*}*/
entities.Customers.Attach(entity);
entities.Entry(entity).State = EntityState.Modified;
entities.SaveChanges();
}
}
public void Destroy(CustomerViewModel customer)
{
if (!UpdateDatabase)
{
var target = GetAll().FirstOrDefault(p => p.CustomerID == customer.CustomerID);
if (target != null)
{
GetAll().Remove(target);
}
}
/*else
{
var entity = new Customer();
entity.customerID = customer.CustomerID;
entities.Customers.Attach(entity);
entities.Customers.Remove(entity);
/*
var orderDetails = entities.Order_Details.Where(pd => pd.ProductID == entity.ProductID);
foreach (var orderDetail in orderDetails)
{
entities.Order_Details.Remove(orderDetail);
}
#1#
entities.SaveChanges();
}*/
}
public CustomerViewModel One(Func<
CustomerViewModel
, bool> predicate)
{
return GetAll().FirstOrDefault(predicate);
}
public void Dispose()
{
entities.Dispose();
}
}
public class GridController : Controller
{
private CustomerService customerService;
public GridController()
{
customerService = new CustomerService(new devDeptMvcContext());
}
protected override void Dispose(bool disposing)
{
customerService.Dispose();
base.Dispose(disposing);
}
public ActionResult Index()
{
PopulateCountries();
return View();
}
private void PopulateCountries()
{
var dataContext = new devDeptMvcContext();
var countries = dataContext.Countries
.Select(c => new CountryViewModel {
CountryID = c.countryID,
CountryName = c.countryName
})
.OrderBy(e => e.CountryName);
ViewData["countries"] = countries;
ViewData["defaultCountry"] = countries.First();
}
public ActionResult ForeignKeyColumn_Read([DataSourceRequest] DataSourceRequest request)
{
return Json(customerService.Read().ToDataSourceResult(request));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ForeignKeyColumn_Update([DataSourceRequest] DataSourceRequest request,
[Bind(Prefix = "models")]IEnumerable<
CustomerViewModel
> customers)
{
if (customers != null && ModelState.IsValid)
{
foreach (var customer in customers)
{
customerService.Update(customer);
}
}
return Json(customers.ToDataSourceResult(request,ModelState));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ForeignKeyColumn_Create([DataSourceRequest] DataSourceRequest request,
[Bind(Prefix = "models")]IEnumerable<
CustomerViewModel
> customers)
{
var results = new List<
CustomerViewModel
>();
if (customers != null && ModelState.IsValid)
{
foreach (var customer in customers)
{
customerService.Create(customer);
results.Add(customer);
}
}
return Json(results.ToDataSourceResult(request, ModelState));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ForeignKeyColumn_Destroy([DataSourceRequest] DataSourceRequest request,
[Bind(Prefix = "models")]IEnumerable<
CustomerViewModel
> customers)
{
foreach (var customer in customers)
{
customerService.Destroy(customer);
}
return Json(customers.ToDataSourceResult(request, ModelState));
}
}
@using Corporate.Models
@(Html.Kendo().Grid<
CustomerViewModel
>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.FirstName).Width(100);
columns.Bound(c => c.LastName).Width(100);
columns.Bound(c => c.Company);
columns.Bound(c => c.City).Width(100);
columns.Bound(c => c.OrderCount).Width(100).Title("Orders");
columns.ForeignKey(c => c.CountryID, (System.Collections.IEnumerable)ViewData["countries"], "CountryID", "CountryName")
.Title("Country").Width(100);
columns.Command(command => command.Edit());
columns.Command(command => command.Destroy());
})
.ToolBar(toolBar =>
{
toolBar.Create();
})
.Editable(editable => editable.Mode(GridEditMode.PopUp))
.Filterable()
.Groupable()
.Pageable()
.Sortable()
//.Scrollable()
.HtmlAttributes(new { style = "height:540px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.ServerOperation(false)
.Events(events => events.Error("errorHandler"))
.Model(model =>
{
model.Id(c => c.CustomerID);
model.Field(c => c.CustomerID).Editable(false);
// model.Field(c => c.CountryID).DefaultValue("ITA");
})
.Read(read => read.Action("ForeignKeyColumn_Read", "Grid"))
.Update(update => update.Action("ForeignKeyColumn_Update", "Grid"))
.Create(create => create.Action("ForeignKeyColumn_Create", "Grid"))
.Destroy(destroy => destroy.Action("ForeignKeyColumn_Destroy", "Grid"))
)
)
<
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);
}
}
</
script
>
The result is a NullReferenceException inside the public ActionResult ForeignKeyColumn_Destroy() method (customer collection is null).
in the view and renaming the ForeignKeyColumn_Destroy() method as Destroy() but they are all blind attempts.