DevExtreme DataGrid ColorBox - devexpress

I am trying to make one of the cells in my datagrid display the "ColorBox" so users can choose a colour.
This is my model:
public class Colour : ModelWrapper
{
public string Name { get; set; }
public string BorderColour { get; set; }
public string BackgroundColour { get; set; }
public string HighlightColour { get; set; }
public string HighlightBorder { get; set; }
public string HighlightBackground { get; set; }
}
This is the code for the grid:
#(Html.DevExtreme().DataGrid<Colour>()
.ID("GridView")
.ShowBorders(true)
.DataSource(d => d.Mvc().Controller("Colours").LoadAction("Get").DeleteAction("HardDelete").UpdateAction("Put").InsertAction("Post").Key("Id"))
.Columns(columns =>
{
columns.AddFor(m => m.Active);
columns.AddFor(m => m.Name);
columns.AddFor(m => m.BorderColour);
columns.AddFor(m => m.BackgroundColour);
columns.AddFor(m => m.HighlightColour);
columns.AddFor(m => m.HighlightBorder);
columns.AddFor(m => m.HighlightBackground);})
.Paging(p => p.PageSize(AppConstants.GridControlPageSize))
.FilterRow(f => f.Visible(true))
.HeaderFilter(f => f.Visible(true))
.GroupPanel(p => p.Visible(true))
.Grouping(g => g.AutoExpandAll(false))
.RemoteOperations(true)
.ColumnChooser(c => c.Enabled(true))
.StateStoring(s => s
.Enabled(true)
.Type(StateStoringType.LocalStorage)
.StorageKey(storageName))
.Editing(editing =>
{
editing.Mode(GridEditMode.Form);
editing.AllowAdding(true);
editing.AllowDeleting(true);
editing.AllowUpdating(true);
})
)
For example, here is one of the columns I want to enable users to use the ColorBox for:
columns.AddFor(m => m.BackgroundColour);
It appears that this should be possible looking at some example code here. (Admittedly this code is marked as "2 years old"):
settings.Columns.Add(column =>
{
column.FieldName = "Colour";
column.Caption = "Colour";
column.Width = 100;
column.ColumnType = MVCxGridViewColumnType.ColorEdit;
ColorEditProperties props = (ColorEditProperties)column.PropertiesEdit;
props.ColumnCount = 8;
props.EnableCustomColors = true;
ColorEditItemCollection colours = new ColorEditItemCollection();
colours.CreateDefaultItems(false);
props.Items.Assign(colours);
});
It seems to be linked to the ColumnType property but when I look at the DevExtreme documentation the column object doesn't appear to have this property.
Can anyone shed any light?

I dont have a machine which runs devextreme right now but the following should be correct.
.OnEditorPreparing("your_js_function")
Put this after columns:
.Columns(columns =>
{
columns.AddFor(m => m.Active);
columns.AddFor(m => m.Name);
columns.AddFor(m => m.BorderColour);
columns.AddFor(m => m.BackgroundColour);
columns.AddFor(m => m.HighlightColour);
columns.AddFor(m => m.HighlightBorder);
columns.AddFor(m => m.HighlightBackground);})
.OnEditorPreparing("your_js_function")
Now a bit of explaination. This js function that you bind to the columns will run for each editor. All columns have a different editor which you can overwrite using this js function.
<script type="text/javascript">
function your_js_function(e) {
if (e.dataField == "BackgroundColour") {
e.editorName = "dxColorBox"; // Changes the editor's type
e.editorOptions.onValueChanged = function (args) {
// Implement your logic here
}
}
}
The official devexpress example is here in the customize editors part. As you will see in the link there are other ways to achieve your result as well. I suggest using a debugger so you can see what e contains.
Also a tip when googling for errors devexpress unfortunately runs on many different versions (VB, C#, Jquery) I think the fastest way would be to find what you are looking for from the documentation.

Related

.NET efcore 7 JSON COLUMN PROBLEMS

as you know, jsoncolumn support has arrived for efcore7.
I quickly used
yes, I had no problems with creating columns with migration. I added new data
but i have the following problem in query operation
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<IdentitySchema>().OwnsMany(
identitySchema => identitySchema.AuthorityCodes, ownedNavigationBuilder =>
{
var q=ownedNavigationBuilder.ToJson();
})
.OwnsMany(
identitySchema => identitySchema.UserIds, ownedNavigationBuilder =>
{
var x= ownedNavigationBuilder.ToJson();
}); ;
base.OnModelCreating(builder);
}
public class UserAg
{
public string UserId { get; set; }
}
_context.IdentitySchema.Select(f => new
{
f.UserIds,
f.AuthorityCodes
}).Where(f => f.UserIds.Any(f => f.UserId == "1")).ToList();

Kendo ui grid fails at canceling the inline edit on aspnet mvc

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))

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; }
}

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);

Entity Framework - Code First - TPH and WillCascadeOnDelete(true)

I have an issue when using TPH and WillCascadeOnDelete(true). When I have the value set on true for cascade on delete my database is not created. The exception message is the following one:
Introducing FOREIGN KEY constraint 'FK_dbo.MembersProfiles_dbo.Contacts_ContactId' on table 'MembersProfiles' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
In order to clear things out here is my model and the mapping used for it.
public class MemberProfile
{
public Guid MemberProfileId { get; set; }
public ICollection<Contact> Contacts { get; set; }
}
public abstract class Contact
{
public Guid ContactId { get; set; }
public Guid AddressId { get; set; }
public Address Address { get; set; }
}
public class PersonContact : Contact
{
public string Profession { get; set; }
public string OrganizationName { get; set; }
}
public class OrganizationContact : Contact
{
public string SalesPhone { get; set; }
public string ServicePhone { get; set; }
}
public class ContactMap : EntityTypeConfiguration<Contact>
{
public ContactMap()
{
ToTable("Contacts");
HasKey(c => c.ContactId);
Property(c => c.ContactId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(c => c.Name).IsRequired().HasMaxLength(50);
Property(c => c.Email).IsRequired().HasMaxLength(150);
Property(c => c.MobilePhone).IsRequired().HasMaxLength(15);
Property(c => c.Description).IsOptional().HasMaxLength(500);
Property(c => c.FixPhone).IsOptional().HasMaxLength(15);
Property(c => c.FaxNumber).IsOptional().HasMaxLength(15);
HasRequired(mp => mp.Address).WithMany().HasForeignKey(mp => mp.AddressId);
HasRequired(mp => mp.Link).WithMany().HasForeignKey(mp => mp.LinkId);
HasRequired(mp => mp.Image).WithMany().HasForeignKey(mp => mp.MediaId);
}
}
public class PersonContactMap : EntityTypeConfiguration<PersonContact>
{
public PersonContactMap()
{
Property(pc => pc.Profession).IsOptional().HasMaxLength(150);
Property(pc => pc.OrganizationName).IsOptional().HasMaxLength(150);
Map(pc => pc.Requires("Discriminator").HasValue("PersonContact").HasColumnType("nvarchar(max)")); }
}
public class OrganizationContactMap : EntityTypeConfiguration<OrganizationContact>
{
public OrganizationContactMap()
{
Property(oc => oc.SalesPhone).IsOptional().HasMaxLength(15);
Property(oc => oc.ServicePhone).IsOptional().HasMaxLength(15);
Map(oc => oc.Requires("Discriminator").HasValue("OrganizationContact").HasColumnType("nvarchar(max)"));
}
}
public class MemberProfileMap : EntityTypeConfiguration<MemberProfile>
{
public MemberProfileMap()
{
ToTable("MembersProfiles");
HasKey(mp => mp.MemberProfileId);
Property(mp => mp.MemberProfileId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(mp => mp.Name).IsRequired().HasMaxLength(50);
Property(mp => mp.DateOfBirth).IsRequired();
Property(mp => mp.Email).IsRequired().HasMaxLength(150);
Property(mp => mp.MobilePhone).IsRequired().HasMaxLength(15);
Property(mp => mp.Summary).IsOptional();
HasRequired(mp => mp.Address).WithMany().HasForeignKey(mp => mp.AddressId).WillCascadeOnDelete(true);
Property(mp => mp.AddressId).HasColumnName("AddressId");
HasOptional(mp => mp.Media).WithMany().Map(mp => mp.MapKey(new[] { "MediaId" })).WillCascadeOnDelete(true);
HasOptional(mp => mp.Tags).WithMany().Map(mp => mp.MapKey(new[] { "TagId" })).WillCascadeOnDelete(true);
HasOptional(mp => mp.Contacts).WithMany().Map(mp => mp.MapKey(new[] { "ContactId" })).WillCascadeOnDelete(true);
}
}
Unfortunately I am not able to realize what am I doing wrong... so any clue would be much appreciated.
P.S: I am using EF 5.0 Code First
See if this BlogPost helps., another option i would try to start adding relation one by one to see where it breaks rather than stacking everything at once. And sometimes it helps to just use individual property mappings rather than Fluent API like you have done. Check out different links on that blog i mentioned above.
Ok, found the issue. I have two tables referring addresses table. In my case both Contacts and MemberProfile hold a reference to Addresses table and in both cases the cascade delete was turned on. Once I turned off the cascade delete on one of the relations everything worked just fine.

Resources