working on a MVC4 project, I'm trying to add a column to my kendo grid that displays an image.
<div id="datagrid">
#(Html.Kendo().Grid<SustIMS.Models.ConcessionModel>()
.Name("datagrid_Concessions")
.Columns(columns =>
{
columns.Bound(c => c.Code).Title(ViewBag.lblCode);
columns.Bound(c => c.Description).Title(ViewBag.lblDescription);
columns.Template(#<text>
<img src='#item.Image' />
</text>
).Title("Image");
})
I've tried that but no luck. Also tried:
columns.Template(#<text>
<img src='../../Images/pic.png' />
</text>
).Title("Image");
The images aren't shown, whether I define the image src in the controller or write it directly in the view.
I've checked both this and this question but the images aren't displayed.
Can anyone help?
EDIT
Here's the Concession Model:
public class ConcessionModel
{
public string Id { get; set; }
public string Code { get; set; }
public string Description { get; set; }
public string TrafficOpeningDate { get; set; }
public string CreationDate { get; set; }
public string CreationUser { get; set; }
public string Image { get; set; }
...
The Image property is a string that contains something like "C:\whatever\pic.png"
Try like this,
columns.Template(e => { }).ClientTemplate("<img src='../../Images/pic.png'/>").Width(140).Title("Image");
DEMO:
View
#(Html.Kendo().Grid<Category>().Name("people")
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(m => m.Id);
})
.Read(read => read.Action("GetCategory", "Category"))
)
.Columns(columns =>
{
columns.Bound(c => c.Id);
columns.Bound(c => c.ImageUrl).ClientTemplate("<img src='" + Url.Content("~/CategoryImage/") + "#=ImageUrl#' alt='#=Name #' Title='#=Name #' height='62' width='62'/>");
})
)
Model
public class Category
{
[ScaffoldColumn(false)]
public int Id { get; set; }
public string Name { get; set; }
[UIHint("FileUpload")]
[Required]
public string ImageUrl { get; set; }
public string FileName { get; set; }
internal static object ToDataSourceResult(Kendo.Mvc.UI.DataSourceRequest dsRequest)
{
throw new NotImplementedException();
}
}
Controller
public static List<Category> Category = new List<Category>();
private int _nextid = 4;
static CategoryController()
{
Category.Add(new Category { Id = 1, Name = "Desert", ImageUrl = "Desert.jpg" });
Category.Add(new Category { Id = 2, Name = "Hydrangeas", ImageUrl = "Hydrangeas.jpg" });
Category.Add(new Category { Id = 3, Name = "Tulips", ImageUrl = "Tulips.jpg" });
}
public ActionResult Index()
{
ViewData["Category"] = Category;
return View();
}
public ActionResult GetCategory([DataSourceRequest] DataSourceRequest dsRequest)
{
var result = Category.ToDataSourceResult(dsRequest);
return Json(result);
}
Related
Can anyone please assist,i have a model that contains a foreign key(ProductCategory).i am trying to call the values of the foreign key but they are not appearing in the view,when i place a breakpoint in the controller all fields appear successful in the raw results view but it seems they are not being passed to the view.
N.B i am using dev express to generate views
public class Product
{
public int Id { get; set; }
public int productCode { get; set; }
public double price { get; set; }
public int ProductCategoryId { get; set; }
public virtual ProductCategory ProductCategory { get; set; }
public Stock itemNo { get; set; }
}
[HttpGet]
public async Task<IActionResult> Get(DataSourceLoadOptions loadOptions) {
var product = _context.Product.Select(i => new {
i.Id,
i.productCode,
i.price,
i.ProductCategoryId,
i.ProductCategory.categoryDescr
});
return Json(await DataSourceLoader.LoadAsync(product, loadOptions));
}
#{
ViewData["Title"] = "Products";
}
<h2 class="content-block">Products</h2>
#(Html.DevExtreme().DataGrid<DevExtremeAspNetCoreApp1.Models.Product>()
.DataSource(ds => ds.Mvc()
.Controller("Products")
.LoadAction("Get")
.InsertAction("Post")
.UpdateAction("Put")
.DeleteAction("Delete")
.Key("Id")
)
.RemoteOperations(true)
.Columns(columns => {
columns.AddFor(m => m.productCode);
columns.AddFor(m => m.price);
columns.AddFor(m => m.ProductCategoryId);
columns.AddFor(m => m.ProductCategory.categoryDescr);
})
.Editing(e => e.Mode(GridEditMode.Popup)
.AllowAdding(true)
.AllowUpdating(true)
.AllowDeleting(true)
.Popup(p=>p
.Title("Product")
.ShowTitle(true)
.Width(500)
.Height(525)
)
)
.Export(e => e.Enabled(true))
)
Try this:
var product = _context.Product.Select(i => new {
i.Id,
i.productCode,
i.price,
i.ProductCategoryId,
ProductCategoryDesc=i.ProductCategory.categoryDescr
});
.....
columns.AddFor(m => m.ProductCategoryDesc);
turns i was passing an anonymous type,correct approach should be:
Controller
public async Task<IActionResult> Get(DataSourceLoadOptions loadOptions) {
var product = _context.Product.Select(i => new {
i.Id,
i.productCode,
i.price,
i.ProductCategoryId,
i.ProductCategory
});
View:
columns.AddFor(m => m.ProductCategory.Id);
I try to populate the dropdownlist from my database. When loading the view, the dropdownlist spinner appears to do something , then the spinner vanishes and the droplist is empty? Can someone propose a solution. Cheers.
QLine.cs
public partial class QLine
{
[Key]
public int lineId { get; set; }
public int networkId { get; set; }
[Required]
[StringLength(50)]
public string lineName { get; set; }
public virtual QNetwork QNetwork { get; set; }
}
LinesDroplistController.cs
public class LinesDroplistController : Controller
{
private KprModel db = new KprModel();
public JsonResult GetMLines()
{
var result = db.QLines.Where(abc => abc.networkId == 1);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
myView.cshtml
#(Html.Kendo().DropDownList()
.Name("LineDropDownList")
.DataTextField("lineName")
.DataValueField("lineId")
.AutoBind(true)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetMLines", "LinesDroplist");
});
})
)
Please try this:
source.Read(read =>
{
read.Action("GetMLines", "LinesDroplist")
}).ServerFiltering(true);
When the serverFiltering is disabled, then the combobox will not make any additional requests to the server.
It worked when changing
var result = db.QLines.Where(abc => abc.networkId == 1);
to
var result = db.QLines.Where(abc => abc.networkId == 1).Select(x => new { x.lineName, x.lineId });
Hi i am binding kendo grid with two tables below is the sequence i used for that.
public class EFEmployeeRepositary : IEmployeeRepositary
{
private EFDBContext context;
public EFEmployeeRepositary()
{
this.context = new EFDBContext();
}
public IQueryable<Entities.Employee> Employees
{
get
{
return context.Employees;
}
}
public IQueryable<Entities.GetEmployeeDetails> GetEmployeesDetails
{
get
{
return context.GetEmployeesDetails;
}
}
}
[System.ComponentModel.DataAnnotations.Schema.Table("Table1", Schema = "dbo")]
public class Employee
{
[System.ComponentModel.DataAnnotations.Key]
public int Staff_Seq_Number { get; set; }
public string Staff_Number { get; set; }
public string Full_Name { get; set; }
public DateTime DOJ { get; set; }
public DateTime DOB { get; set; }
public string Email_Address { get; set; }
public string Nationality_Code { get; set; }
public int Age { get; set; }
public string Marital_Status_Code { get; set; }
public string Gender_Code { get; set; }
}
[System.ComponentModel.DataAnnotations.Schema.Table("Table2", Schema = "dbo")]
public class GetEmployeeDetails
{
[System.ComponentModel.DataAnnotations.Key]
public int Staff_Seq_Number { get; set; }
public int Matrix_ID { get; set; }
public int Grade_ID { get; set; }
public int Position_ID { get; set; }
}
public class MergeTables
{
public Employee employees { get; set; }
public GetEmployeeDetails GetEmployeesDetails { get; set; }
}
This is my Interface EmployeeRepository class where i added both class
public interface IEmployeeRepositary
{
IQueryable<Employee> Employees { get; }
IQueryable<GetEmployeeDetails> GetEmployeesDetails { get; }
IQueryable<MergeTables> GetMergeTables { get; }
}
This is my dbcontext class
public DbSet<Employee> Employees
{
get;
set;
}
public DbSet<EmployeeHistory> EmployeesHistory
{
get;
set;
}
public DbSet<MergeTables> GetMergeTables
{
get;
set;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
}
This is my controller where called this interface repository
private IEmployeeRepositary employeeRepositary;
public DashboardController(IEmployeeRepositary pEmployeeRepositary)
{
this.employeeRepositary = pEmployeeRepositary;
}
and in same controller i have this actionresult function
public ActionResult Employee_Read([DataSourceRequest] DataSourceRequest request)
{
var p = (from emp in this.employeeRepositary.Employees
join empdetails in this.employeeRepositary.GetEmployeesDetails on emp.Staff_Seq_Number equals empdetails.Staff_Seq_Number
select new MergeTables()
{
});
return Json(p, JsonRequestBehavior.AllowGet);
}
1st Issue: when i am running this i am getting error that "one or more validation errors were detected during model generation has no key defined" which new class MergeTables i created there i am getting issue.
2nd Issue: if i remove mergetables from Repository and and DBContext class this query is working fine but no data is showing in kendo grid
i have shown here two models but more than two models i used and binding in Action result.
Below is the kendo grid code:
#(Html.Kendo().Grid<GEMS.Domain.Entities.MergeTables>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.employees.Staff_Number).Title("EmployeeId");
columns.Bound(p => p.employees.Full_Name).Title("Name");
columns.Bound(p => p.employees.Age).Title("Age");
columns.Bound(p => p.employees.Email_Address).Title("EmailId");
columns.Bound(p => p.GetHierarchyTemp.Department).Title("Department");
columns.Bound(p => p.employees.DOB).Title("Date of birth");
columns.Bound(p => p.employees.DOJ).Title("Date of joining");
columns.Bound(p => p.employees.Marital_Status_Code).Title("Marital Status");
columns.Bound(p => p.employees.Nationality_Code).Title("Nationality Code");
})
.Scrollable()
.Groupable()
.Sortable()
.ColumnMenu()
.Filterable()
.ClientDetailTemplateId("template")
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Multiple)
.Type(GridSelectionType.Cell))
.Navigatable()
.AllowCopy(true)
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(10))
.HtmlAttributes(new { style = "height:380px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Employee_Read", "Dashboard"))
)
.Events(events => events.DataBound("dataBound"))
)
can any one help me about these two issues how to fix it
use the word [Key] above your model items.
example:
class telefoon{
[Key]
Int id {get:set}
int number{get:set}
}
like this
I've This Kendo UI Grid and I'm populating the grid with the values from a couple of tables
I've this GetBrands Method and I can get vales from other tables as you can see in the given method what I can't get is the vale from the TemData["CompanyId"]
how can I get CompanyName from This
public ActionResult GetBrands([DataSourceRequest] DataSourceRequest request)
{
var result= new DataSourceResult();
IQueryable<Brand> brands = null;
try
{
brands = db.Brands;
result = brands.AsQueryable()
.ToList()
.Select(b => new BrandListViewModels()
{
BrandName = b.BrandName,
ProductGroupCode = b.ProductGroupCode !=null? db.ProductGroups.FirstOrDefault(p => p.ProductGroupCode==b.ProductGroupCode).ProductGroupName:"N/A",
ProductSubGroupCode = b.ProductGroupCode != null ? db.ProductSubGroups.FirstOrDefault(p => p.ProductSubGroupCode == b.ProductSubGroupCode).ProductSubGroupName : "N/A",
// CompanyId = Convert.ToInt32(TempData["CompanyId"]) !=null? int.TryParse(db.Companies.FirstOrDefault(c=>c.Id==b.CompanyId).CompanyName, out id):"N/A"
}).OrderBy(b=>b.CompnayName)
.ToDataSourceResult(request);
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
//Temporary storing notification message
TempData["MESSAGE"] = js.Serialize(new { message = "Error has been occured while populating brands", type = "E" });
}
return Json(result,JsonRequestBehavior.AllowGet);
}
I tried To convert It and do lots of other stuff but its not working Its type is Int
Edit
Here is my BrandListViewModel
public class BrandListViewModels
{
public string ProductGroupCode { get; set; }
public string ProductSubGroupCode { get; set; }
public string BrandCode { get; set; }
public string BrandName { get; set; }
public int CompanyId { get; set; }
public string CompnayName { get; set; }
}
Here is my Grid
#(Html.Kendo().Grid(Model)
.Name("BrandGrid")
.Columns(columns =>
{
columns.Bound(c => c.CompanyId).Title("Company");
columns.Bound(c => c.BrandName).Title("Brand");
columns.Bound(c => c.ProductGroupCode).Title("Product Group");
columns.Bound(c => c.ProductSubGroupCode).Title("Product Sub Group");
I've used Kendo Grid for showing data.It seems data is passed correctly because when I tracing my code in run time, I see there are some data in result but Kendo Grid couldn't show the data.
How can I solve this problem?
EDIT DESCRIPTION:
I found cause of problem but I cannot solve it.
If I remove this line in my ViewModel in QueryBuilder() method,
Tags = article.ArticleTags.Where(c => c.ArticleId == article.Id).Select(b => b.Tag).Distinct().ToList()
Grid show data but I need values of Tags. why this line of code has been caused the problem?
Tag model:
public class Tag : Entity, ITag
{
public Tag()
{
}
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual bool? IsActive { get; set; }
[Range(1, 4)]
public virtual int Size { get; set; }
public virtual ISet<ArticleTag> ArticleTags { get; set; }
public virtual ISet<ProjectTag> ProjectTags { get; set; }
}
my grid:
#using Jahan.Blog.Web.Mvc.HtmlHelpers
#using Kendo.Mvc.UI
#using Kendo.Mvc.UI.Fluent
#model IEnumerable<Jahan.Blog.ViewModel.ArticleViewModel>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div style="width: 100%;">
#(Html.Kendo().Grid<Jahan.Blog.ViewModel.ArticleViewModel>()
.Name("ArticleAdmin").Navigatable()
.Resizable(c => c.Columns(true))
.HtmlAttributes(new { #class = "cursorLink", #style = "width: 1000px;height:auto;overflow: scroll;" })
.Columns(columns =>
{
columns.Bound(p => p.Id).Width(100);
columns.Bound(p => p.Title).Width(200);
columns.Command(command => command.Destroy()).Width(170);
})
.ToolBar(toolbar =>
{
toolbar.Create();
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Navigatable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(10)
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(p => p.Id))
.Create("Editing_Create", "ArticleAdmin")
.Read("Editing_Read", "ArticleAdmin")
.Update("Editing_Update", "ArticleAdmin")
.Destroy("Editing_Destroy", "ArticleAdmin")
))
</div>
in my Controller:
public ActionResult Index([DataSourceRequest] DataSourceRequest request)
{
List<ArticleViewModel> instance = new ArticleViewModel().FindByCriteria().ToList();
return View(instance); // There are some data. instance.count = 2
}
public ActionResult Editing_Read([DataSourceRequest] DataSourceRequest request)
{
List<ArticleViewModel> instance = new ArticleViewModel().FindByCriteria().ToList();
DataSourceResult dsRequest = instance.ToDataSourceResult(request); // There are some data.
return Json(dsRequest, JsonRequestBehavior.AllowGet);
}
my ViewModel:
public class ArticleViewModel : IArticle, IDateTracking
{
public ArticleViewModel()
{
}
public int? UserId { get; set; }
public string Title { get; set; }
public string Summary { get; set; }
public string Description { get; set; }
public decimal? RateCounter { get; set; }
public int? LikeCounter { get; set; }
public bool IsActive { get; set; }
public bool IsActiveNewComment { get; set; }
public IList<Comment> Comments { get; set; }
public ISet<Rating> Ratings { get; set; }
public IList<AttachmentFile> AttachmentFiles { get; set; }
public ISet<ArticleTag> ArticleTags { get; set; }
public ISet<ArticleLike> ArticleLikes { get; set; }
public int Id { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
[UIHint("_TagsOfArticle")]
public virtual IList<Tag> Tags { get; set; }
public virtual int NumberOfComments { get; set; }
public virtual User User { get; set; }
private IQueryable<ArticleViewModel> QueryBuilder()
{
ArticleRepository repository = new ArticleRepository();
IQueryable<ArticleViewModel> query = repository.FindAll().Select(article => new ArticleViewModel
{
Id = article.Id,
AttachmentFiles = article.AttachmentFiles.Where(a => a.ArticleId == article.Id).Distinct().ToList(),
Comments = article.Comments.Where(c => c.ArticleId == article.Id).ToList(),
CreatedDate = article.CreatedDate,
//Description = article.Description,
IsActive = article.IsActive,
IsActiveNewComment = article.IsActiveNewComment,
LikeCounter = article.LikeCounter,
ModifiedDate = article.ModifiedDate,
NumberOfComments = article.Comments.Count(c => c.ArticleId == article.Id),
RateCounter = article.RateCounter,
//Summary = article.Summary,
Tags = article.ArticleTags.Where(c => c.ArticleId == article.Id).Select(b => b.Tag).Distinct().ToList(),
Title = article.Title,
UserId = article.UserId
});
return query;
}
public virtual IQueryable<ArticleViewModel> QueryBuilderByCriteria(Expression<Func<ArticleViewModel, bool>> predicate = null, params Expression<Func<ArticleViewModel, object>>[] includeProperties)
{
IQueryable<ArticleViewModel> items = QueryBuilder();
if (includeProperties != null)
{
foreach (Expression<Func<ArticleViewModel, object>> includeProperty in includeProperties)
{
items = items.Include(includeProperty);
}
}
if (predicate != null)
return items.Where(predicate);
return items;
}
public virtual IEnumerable<ArticleViewModel> FindByCriteria(Expression<Func<ArticleViewModel, bool>> predicate = null, params Expression<Func<ArticleViewModel, object>>[] includeProperties)
{
List<ArticleViewModel> result = QueryBuilderByCriteria(predicate, includeProperties).ToList();
return result;
}
public virtual ArticleViewModel FindByArticleId(int articleId)
{
ArticleViewModel result = QueryBuilder().FirstOrDefault(a => a.Id == articleId);
return result;
}
}
For solving the problem I performed some changes.
1) Instead of using Tag model, I've used TagViewModel.I've figured out Tag model, itself is cause of problem! I don't know why does it cause. Then I decided to create a TagViewModel that it has simplified of Tag class.
public class TagGridViewModel
{
public virtual int Id { get; set; }
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual bool? IsActive { get; set; }
public virtual int Size { get; set; }
public static List<TagGridViewModel> GetByArticleId(int articleId)
{
List<TagGridViewModel> tags = new List<TagGridViewModel>();
List<Tag> tagsPerArticle = ArticleRepository.Instance.GetTagsByArticleId(articleId);
foreach (var tag in tagsPerArticle)
{
tags.Add(new TagGridViewModel
{
Id = tag.Id,
IsActive = tag.IsActive,
Description = tag.Description,
Title = tag.Title,
Size = tag.Size
});
}
return tags;
}
}
And in ArticleViewModel:
public List<TagGridViewModel> Tags { get; set; }
And in FindByCriteria method:
public virtual IEnumerable<ArticleViewModel> FindByCriteria(Expression<Func<ArticleViewModel, bool>> predicate = null, params Expression<Func<ArticleViewModel, object>>[] includeProperties)
{
List<ArticleViewModel> result = new List<ArticleViewModel>();
var query = QueryBuilderByCriteria(predicate, includeProperties);
foreach (var articleViewModel in query)
{
articleViewModel.Tags = TagGridViewModel.GetByArticleId(articleViewModel.Id);
articleViewModel.Owner = AppUserStore.Instance.FindByIdAsync(int.Parse(articleViewModel.UserId.ToString())).Result.UserName;
result.Add(articleViewModel);
}
return result;
}
After these changes, Grid shows data.