Kendo ui grid fails at canceling the inline edit on aspnet mvc - asp.net

I have come across a frustrating issue lately. I'm using kendi ui Grid on asp.net mvc ... the problem I'm running into is when I switch grid editable mode on and add the edit command and model Id, everything seems to be working but there are issues. First it doesn't hit the edit action on the controller then if I cancel the edit, the row is going to disappear!
This is my model
public class ContactInformation
{
[Key]
[ScaffoldColumn(false)]
public long ContactInfoId { get; set; }
public string Position { get; set; }
[Required]
public string Name { get; set; }
public string PhoneNumber { get; set; }
public string CodeToPerson { get; set; }
public string Fax { get; set; }
public string CellPhoneNumber { get; set; }
public string Email { get; set; }
public virtual Client Client { get; set; }
}
This is the controller
public class ContactsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: dashboard/Contacts
public ActionResult Default(string id)
{
if(id != null)
{
ViewBag.clientGuid = id;
var model = db.Clients.SingleOrDefault(x=>x.ClientGuid == id);
model.BillingAddresses = db.BillingAddresses.Where(x => x.Client.ClientId == model.ClientId).ToList();
return View(model);
}
return View();
}
public ActionResult Contacts_Read([DataSourceRequest]DataSourceRequest request, string id)
{
var contacts = (id != null) ?
db.ContactInfos.Where(x => x.Client.ClientGuid == id).ToList() :
db.ContactInfos.ToList();
return Json(GetContacts(contacts).ToDataSourceResult(request),JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Contacts_Create([DataSourceRequest]DataSourceRequest request,ContactInformation model)
{
// Todo: save the model
return Json(ModelState.ToDataSourceResult());
}
[HttpPost]
public ActionResult Contacts_Update([DataSourceRequest]DataSourceRequest request, ContactInformation model)
{
if(model != null)
{
var contactToUpdate = db.ContactInfos.Find(model.ContactInfoId);
contactToUpdate.Name = model.Name;
contactToUpdate.Position = model.Position;
contactToUpdate.PhoneNumber = model.PhoneNumber;
contactToUpdate.CodeToPerson = model.CodeToPerson;
contactToUpdate.CellPhoneNumber = model.CellPhoneNumber;
contactToUpdate.Fax = model.Fax;
contactToUpdate.Email = model.Email;
contactToUpdate.Client = db.Clients.Find(model.Client.ClientId);
db.SaveChanges();
}
return Json(ModelState.ToDataSourceResult());
}
public IEnumerable<ContactInformation> GetContacts(List<ContactInformation> contacts)
{
return contacts.Select(contactInfo => new ContactInformation
{
Position = contactInfo.Position,
Name = contactInfo.Name,
PhoneNumber = contactInfo.PhoneNumber,
CodeToPerson = contactInfo.CodeToPerson,
Fax = contactInfo.Fax,
CellPhoneNumber = contactInfo.CellPhoneNumber,
Email = contactInfo.Email,
Client = new Client()
{
CompanyName = contactInfo.Client.CompanyName,
IndustryCategory = contactInfo.Client.IndustryCategory,
IndustrySubCategory = contactInfo.Client.IndustrySubCategory
}
});
}
}
This is the view
#(Html.Kendo().Grid<ContactInformation>().Name("Contacts")
.Columns(
columns.Bound(c => c.Client.IndustryCategory).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.Client.IndustrySubCategory).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.Name).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.Position).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.PhoneNumber).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.CodeToPerson).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.CellPhoneNumber).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.Fax).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Bound(c => c.Email).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
columns.Command(command =>
{
command.Edit();
}).Width(100);
})
.ToolBar(tools =>
{
tools.Excel();
})
.Excel(excel => excel
.FileName("ContactsData.xlsx")
.Filterable(true)
.ProxyURL(Url.Action("Excel_Export_Save"))
)
.Filterable(ftb => ftb.Mode(GridFilterMode.Row))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.Scrollable()
.Sortable()
.Groupable()
.Events(events=>events.Cancel("error_handler"))
.Editable(editable => editable.Mode(GridEditMode.InLine))
.HtmlAttributes(new { style = "height:500px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Model(Model=> {
Model.Id(c => c.ContactInfoId);
Model.Field(c => c.Client.IndustryCategory).Editable(false);
Model.Field(c => c.Client.IndustrySubCategory).Editable(false);
})
//.Create(create => create.Action("Contacts_Create", "Contacts"))
.Read(read => read.Action("Contacts_Read", "Contacts", new { id = ViewBag.clientGuid }))
.Update(update => update.Action("Contacts_Update", "Contacts", new { id = ViewBag.clientGuid }))
.PageSize(20)
)
.ColumnMenu()
)
<script type="text/javascript">
function error_handler(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 interesting thing, there is another model called inquiry in the project that has grid the same as this one and it works quite fine. Actually, they are quite identical but I couldn't figure it out why this doesn't work like the other!

First thing I see here is that your method in controller is HttpPost but in the definition of update function (on Telerik grid) you didn't specify it. It means, that grid is trying to trigger default one - and it is HttpGet -> that's why update is not triggered.
You need to define that update method is Post
.Update(update => update.Action("Contacts_Update", "Contacts", new { id = ViewBag.clientGuid }).Type(HttpVerbs.Post))

Related

use a control inside a column on a telerik grid

In asp.net mvc page im using a telerik grid that looks like this
<div>
#(Html.Kendo().Grid<Project.Models.Bench>
()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.name).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")));
columns.Bound(p => p.seatsCount).Filterable(ftb => ftb.Cell(cell => cell.Operator("gte")));
columns.Bound(p => p.bookedSeats).Filterable(ftb => ftb.Cell(cell => cell.Operator("gte")));
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable(ftb => ftb.Mode(GridFilterMode.Row))
//.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
//.ServerOperation(true)
.Read(read => read.Action("GetBenches", "home"))
)
)
</div>
this is my Bench class:
public class Bench
{
public int id { get; set; }
public string name { get; set; }
public bool bookable { get; set; }
public int zone { get; set; }
public int seatsCount { get; set; }
public string area { get; set; }
public int bookedSeats { get; set; }
public int freeSeats { get; set; }
}
and my GetBenches method on HomeController
public async Task<ActionResult> GetBenches([DataSourceRequest] DataSourceRequest request)
{
BenchesService bService = new BenchesService();
List<Bench> obj = await bService.getBenches();
return Json(obj.Select(s => new Bench
{
id = s.id,
bookable = s.bookable,
name = s.name,
seatsCount = s.seatsCount,
zone = s.zone,
freeSeats = s.freeSeats,
area = s.area,
bookedSeats = s.bookedSeats
}).Distinct().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
i would like to know if i add a .ClientTemplate to one of the columns if i can add a control of this type inside the cell (the one on the "Benefit components" column)
Well, you could start with something like this perhaps:
#(Html.Kendo().Grid<Project.Models.Bench>
()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.name).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")));
columns.Bound(p => p.Variance).Title("Booked")
.ClientTemplate(Html.Kendo().Sparkline()
.Name("booked_#=name#"")
.Type(SparklineType.Column)
.Tooltip(tooltip => tooltip.Format("{0} booked"))
.DataSource(
.DataSource(ds => ds.Ajax()
.Read(read => read.Action("Read", "MyController", new { myId = Model.MyID })
)
.ToClientTemplate()
.ToHtmlString()
);
})
...

How to add a dropdown into telerik grid for asp.net mvc?

I have a requirement to implement this telerik grid in my application(You can check the grid demo here:- GRID ). I want one of the column in the grid to be a dropdown control, which displays all the values on click of it.
I followed few articles available on telerik site(Article1), but still I could not get the functionality implemented.
Basically, I am getting data for the dropdown from DB and saving it into a viewstate, in the controller. Which I later Bind it to the editor template(of dropdown).
I have shared my code for your reference. Please let me know if you any suggestions.
Here is my source code:-
1. Grid's source code
#(Html.Kendo().Grid<Lamp.Model.RemedyOrHpnaCaseModel>()
.Name("Grid")
.EnableCustomBinding(true)
.Columns(columns =>
{
columns.Bound(p => p.SystemName).Width("20%");
columns.Bound(p => p.PartNumber).Width("20%");
columns.Bound(p => p.Manufacturer).Width("20%");
columns.Bound(p => p.CasePartNumber).Width("20%");
columns.Bound(p => p.Notes).Title("Notes");
columns.Command(command => command.Destroy()).Width(110);
})
.ToolBar(toolbar =>
{
toolbar.Create();
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Navigatable()
.Sortable()
.Scrollable()
.Filterable()
.HtmlAttributes(new { style = "height:460px" })
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(10)
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(p => p.PartNumber);
model.Field(p => p.PartNumber).Editable(false);
model.Field(p => p.SystemName).Editable(false);
model.Field(p => p.Manufacturer).Editable(false);
})
.Read(read => read.Action("RemedyOrHpnaCase_Read", "LCMLookup"))
.Update(update => update.Action("RemedyOrHpnaCase_Update", "LCMLookup"))
)
.Resizable(resize => resize.Columns(true))
)
Source Code of the editor template(for DropDown)
#(Html.Kendo().DropDownList<Lamp.Model.CasePartNumber>()
.Name("CasePartNumber") // Name of the widget should be the same as the name of the property
.DataValueField("DeviceID") // The value of the dropdown is taken from the CasePartID property
.DataTextField("PartNumber") // The text of the items is taken from the CasePartName property
.BindTo((System.Collections.IEnumerable)ViewData["CasePartNumber"]) // A list of all casepartnumber which is populated in the controller
)
3.Source code of the controller
[HttpGet]
public ActionResult RemedyOrHpnaCase()
{
LCMLookupDAO lcmLookupDAO = new LCMLookupDAO();
ViewData["CasePartNumber"] = lcmLookupDAO.PopulateCasePartNumber();
return View("RemedyOrHpnaCase", model);
}
Source code of Model class
public class RemedyOrHpnaCaseModel
{
public string SystemName { get; set; }
public string PartNumber { get; set; }
public string Manufacturer { get; set; }
[UIHint("CasePartNumberEditor")]
public IEnumerable CasePartNumber { get; set; }
public string Notes { get; set; }
}
public class CasePartNumber
{
public int? DeviceID { get; set; }
public string PartNumber { get; set; }
}

Kendo Grid AJAX Bound Not Updating MVC4

I am trying to get my grid to update for the opt-in status, but when I hit update no action occurs. I an using ajax binding with a model and entity framework. When I hit cancel it will follow this method. I am not sure what I am missing as everything else functions and compiles.
View
<div class="row">
<h2>PQA Opt-In</h2>
<br />
#(Html.Kendo().Grid<TelerikMvcApp1.Models.PQAViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(opt => opt.Jobber).Width(90);
columns.Bound(opt => opt.Dealer).Width(95);
columns.Bound(opt => opt.OptInd).Width(110);
columns.Bound(opt => opt.establish_date_time);
columns.Bound(opt => opt.establish_id);
columns.Command(commands =>
{
commands.Edit();
}).Title("Commands").Width(200);
})
.DataSource(datasource => datasource
.Ajax()
.Model(model =>
{
model.Id(opt => opt.Jobber);
model.Field(opt => opt.Jobber).Editable(false);
model.Field(opt => opt.Dealer).Editable(false);
model.Field(opt => opt.establish_date_time).Editable(false);
model.Field(opt => opt.establish_id).Editable(false);
})
.PageSize(20)
.Read(read => read.Action("ProductQualityFileFull_Read", "PQA"))
.Update(update => update.Action("Opt_Update", "PQA"))
)
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Filterable()
.Pageable()
)
</div>
Controller
sing System;
using System.Linq;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using TelerikMvcApp1.Models;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
namespace TelerikMvcApp1.Controllers
{
public class PQAController : Controller
{
public ActionResult Baseline()
{
return View();
}
public ActionResult ProductQualityFileFull_Read([DataSourceRequest] DataSourceRequest
request)
{
using (var pqa = new PQAEntities())
{
IQueryable<ProductQualityFileFull> opt = pqa.ProductQualityFileFulls;
DataSourceResult result = opt.ToDataSourceResult(request, ProductQualityFileFull =>
new PQAViewModel
{
Jobber = ProductQualityFileFull.Jobber,
Dealer = ProductQualityFileFull.Dealer,
OptInd = ProductQualityFileFull.OptInd,
establish_date_time = ProductQualityFileFull.establish_date_time,
establish_id = ProductQualityFileFull.establish_id
});
return Json(result);
}
}
public ActionResult UpdateOptIn()
{
return View();
}
public ActionResult Opt_Update([DataSourceRequest] DataSourceRequest request,
PQAViewModel opt)
{
if (ModelState.IsValid)
{
using (var pqa = new PQAEntities())
{
var entity = new ProductQualityFileFull
{
Jobber = opt.Jobber,
Dealer = opt.Dealer,
OptInd = opt.OptInd,
establish_date_time = opt.establish_date_time,
establish_id = opt.establish_id
};
pqa.ProductQualityFileFulls.Attach(entity);
pqa.Entry(entity).State = EntityState.Modified;
pqa.SaveChanges();
}
}
return Json(new[] { opt }.ToDataSourceResult(request, ModelState));
}
}
}
Model
namespace TelerikMvcApp1.Models
{
public class PQAViewModel
{
public string Jobber { get; set; }
public int Dealer { get; set; }
public int OptInd { get; set; }
public DateTime establish_date_time { get; set; }
public string establish_id { get; set; }
}
}
You have made all your columns non-editable - which means you will not make any changed to the model. And if no change is made - no update request is performed. Make a change to your model and the update should be triggered.

Ajax Binding a Kendo Grid with Asp.Net MVC doesn't display anything

I am trying to bind a Kendo Grid with Asp.Net MVC. I show that grid in a detail page View with a lot of other fields...
The records are coming correctly but nothing is displayed in the grid.
Here is the Grid code, in the user control (ascx), of the View:
<% Html.Kendo().Grid<Web.Areas.WorkOrder.ViewModels.PartListViewModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.GlassType);
columns.Bound(p => p.WorkType);
columns.Bound(p => p.PartNumber);
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetPartListInfo", "Claim", new { id = Model.JobId }))
.PageSize(5)
.ServerOperation(false)
)
.Pageable()
.Sortable()
.Groupable()
.Filterable()
.Render();
%>
The Model View looks like this:
public IEnumerable<PartListViewModel> PartList { get; set; }
public string VIN { get; set; }
public string Invoice { get; set; }
public string MileageKM { get; set; }
public EntityModel Provider { get; set; }
public string Comments { get; set; }
…etc, etc
This is the code from my Controller:
public ActionResult GetPartListInfo([DataSourceRequest] DataSourceRequest request, string id)
{
XrmServiceContext xrmServiceContext = new XrmServiceContext();
workorder workOrder = xrmServiceContext.workorderSet.Where(i => i.Id == new Guid(id)).FirstOrDefault();
IEnumerable<PartListViewModel> parts = (xrmServiceContext.workorderproductSet.Where(prod => prod.WorkOrder.Id == workOrder.Id))
.Select(x => new PartListViewModel
{
WOId = id,
Id = x.f1_Product.Id.ToString(),
Quantity = 3,
PartNumber = "WS",,
WorkType = "Repair",
GlassType = "Windshield",
Price = 133
}).ToList();
return Json(parts.ToDataSourceResult(request));
}
Am I missing something in my configuration? I am wondering what is going wrong with it?
Thanks for any help you can provide.
try adding this to allow a get:
return Json(parts.ToDataSourceResult(request),JsonRequestBehavior.AllowGet);

Add css class to row in MVCContrib grid

I'm displaying a grid of data, and one of the attributes is an expiration date. If the expiration date is less than 60 days away, I'd like to highlight the row.
I found this post, and used the answer there to use the RowAttributes function:
#Html.Grid(Model.PagedList).Columns(column =>{
column.For(m => m.Name);
column.For(m => m.ExpirationDate);
}).Sort(Model.GridSortOptions)
.Attributes(#class => "grid")
.RowAttributes(m => new MvcContrib.Hash(#class =>
(m.Item.ExpirationDate.Value.AddDays(-60) < DateTime.Now)) ? "warning" : "")
But I get a compilation error saying:
Cannot implicitly convert type 'MvcContrib.Hash' to 'bool'
What am I doing wrong here?
The following works fine for me:
Model:
public class MyViewModel
{
public DateTime? ExpirationDate { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new[]
{
new MyViewModel { ExpirationDate = DateTime.Now.AddDays(70) },
new MyViewModel { ExpirationDate = DateTime.Now.AddDays(30) },
new MyViewModel { ExpirationDate = DateTime.Now.AddDays(90) },
};
return View(model);
}
}
View:
#using MvcContrib.UI.Grid
#using MvcContrib
#model IEnumerable<MyViewModel>
#(Html
.Grid(Model)
.Columns(column => {
column.For(m => m.ExpirationDate);
})
.Attributes(#class => "grid")
.RowAttributes(m => new Hash(#class => (m.Item.ExpirationDate.Value.AddDays(-60) < DateTime.Now) ? "warning" : "" ))
)
You could also write an extension method for your model:
public static class RowAttributesExtensions
{
public static Hash GetRowAttributes(this MyViewModel model)
{
return new Hash(#class => (model.ExpirationDate.Value.AddDays(-60) < DateTime.Now) ? "warning" : "");
}
}
and then:
#(Html
.Grid(Model)
.Columns(column => {
column.For(m => m.ExpirationDate);
})
.Attributes(#class => "grid")
.RowAttributes(m => m.Item.GetRowAttributes())
)
which makes it more readable.

Resources