Data not showing in Kendo MVC Grid - asp.net-mvc

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.

Related

Write query for search functionality in C#/ASP.NET MVC

I'm trying to include a search functionality in a ASP.NET Web Application using a search textbox. I have a controller (HomeController) which include an Index (list all data) and a Search (based on user input) Action Method but I'm having trouble writing the code/query for the Search Action Method. Any help would be appreciated. Thanks
//textbox from the View
#using (Html.BeginForm("Search", "Home"))
{
#Html.Editor("SearchBox")
<input type="submit" value="Search" />
}
//The model
public class EventViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime StartDateTime { get; set; }
public TimeSpan? Duration { get; set; }
public string Author { get; set; }
public string Location { get; set; }
public static Expression<Func<Event, EventViewModel>> ViewModel
{
get
{
return e => new EventViewModel()
{
Id = e.Id,
Title = e.Title,
StartDateTime = e.StartDateTime,
Duration = e.Duration,
Location = e.Location,
Author = e.Author.FullName
};
}
}
}
public class UpcomingPassedEventsViewModel
{
public IEnumerable<EventViewModel> UpcomingEvents { get; set; }
public IEnumerable<EventViewModel> PassedEvents { get; set; }
}
//controller
public class HomeController : BaseController
{
public ActionResult Index()
{
var events = this.db.Events
.OrderBy(e => e.StartDateTime)
.Where(e => e.IsPublic)
.Select(EventViewModel.ViewModel);
var upcomingEvents = events.Where(e => e.StartDateTime > DateTime.Now);
var passedEvents = events.Where(e => e.StartDateTime <= DateTime.Now);
return View(new UpcomingPassedEventsViewModel()
{
UpcomingEvents = upcomingEvents,
PassedEvents = passedEvents
});
}
public ActionResult Search(string SearchBox)
{
}

Database-First & Error: Unable to determine a valid ordering for dependent operations

I have a problem with the project I am working on. On POST:Edit, it saves my changes. On POST:Create, I receive this error: "Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values."
So I did what my teachers taught us in College: I just Googled it. The answers however were suggesting to change the ModelBuilder-fluent API. I do not think this would be inappropriate since I use Database-First approach (It says it is only for Code-First) AND my Save is functional in Edit. Since I wanted to work with ViewModels, I followed this tutorial. I even found and posted a solution for the tutorial about the Create method to help me with my problem. Please help me. I am about to throw my computer out of the window. Which is kind of complicated because they are made of tempered glass.
So here's the metadata for my model (with minimal data annotation for readability sake:
public partial class Employe
{
sealed class Metadata
{
[Key]
public int IdEmploye { get; set; }
public string NomEmploye { get; set; }
public string PrenomEmploye { get; set; }
[ForeignKey("TitreEmploye_IdTitre")]
public int IdTitre { get; set; }
[ForeignKey("Departement_IdDepartement")]
public int IdDepartement { get; set; }
[ForeignKey("Employe_IdSuperviseur")]
public int IdSuperviseur { get; set; }
public System.DateTime DateEmbauche { get; set; }
public Nullable<System.DateTime> DateDepart { get; set; }
public string StatutEmploye { get; set; }
[ForeignKey("Employeur_IdEmployeur")]
public int IdEmployeur { get; set; }
[ForeignKey("Localisation_IdLocalisation")]
public int IdLocalisation { get; set; }
public string Langue { get; set; }
public Nullable<bool> CarteAcces { get; set; }
[ForeignKey("TelephoneBureau_IdTelephoneBureau")]
public Nullable<int> IdTelephoneBureau { get; set; }
public Nullable<bool> CarteAffaire { get; set; }
public string AdresseCourriel { get; set; }
public bool CodeAlarme { get; set; }
public System.DateTime DateNaissance { get; set; }
public Nullable<bool> IsSuperviseur { get; set; }
public Nullable<bool> IsActif { get; set; }
}
}
}
Here's my problematic(?) model:
public partial class Employe
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Employe()
{
this.AccesApplicatif1 = new HashSet<AccesApplicatif>();
this.TelephoneCellulaire1 = new HashSet<TelephoneCellulaire>();
this.CleBatiment1 = new HashSet<CleBatiment>();
this.EquipementInfo = new HashSet<EquipementInfo>();
this.GroupeSecurite1 = new HashSet<GroupeSecurite>();
this.VehiculeCompagnie1 = new HashSet<VehiculeCompagnie>();
this.Employe1 = new HashSet<Employe>();
}
public int IdEmploye { get; set; }
public string NomEmploye { get; set; }
public string PrenomEmploye { get; set; }
public int IdTitre { get; set; }
public int IdDepartement { get; set; }
public int IdSuperviseur { get; set; }
public System.DateTime DateEmbauche { get; set; }
public Nullable<System.DateTime> DateDepart { get; set; }
public string StatutEmploye { get; set; }
public int IdEmployeur { get; set; }
public int IdLocalisation { get; set; }
public string Langue { get; set; }
public Nullable<bool> CarteAcces { get; set; }
public Nullable<int> IdTelephoneBureau { get; set; }
public Nullable<bool> CarteAffaire { get; set; }
public string AdresseCourriel { get; set; }
public bool CodeAlarme { get; set; }
public System.DateTime DateNaissance { get; set; }
public Nullable<bool> IsSuperviseur { get; set; }
public Nullable<bool> IsActif { get; set; }
public virtual Departement Departement { get; set; }
public virtual Employeur Employeur { get; set; }
public virtual Localisation Localisation { get; set; }
public virtual TelephoneBureau TelephoneBureau { get; set; }
public virtual TitreEmploye TitreEmploye { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<AccesApplicatif> AccesApplicatif1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<TelephoneCellulaire> TelephoneCellulaire1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<CleBatiment> CleBatiment1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<EquipementInfo> EquipementInfo { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<GroupeSecurite> GroupeSecurite1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<VehiculeCompagnie> VehiculeCompagnie1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Employe> Employe1 { get; set; }
public virtual Employe Employe2 { get; set; }
public string NomSuperviseur
{
get
{
return string.Format("{0} {1}", PrenomEmploye, NomEmploye);
}
}
}
As I said, since I wanted to work with ViewModels, here's the culprit:
public partial class EmployeVM
{
public Employe Employe { get; set; } //Employe
public string NomEmploye { get; set; } //Employe
public string PrenomEmploye { get; set; } //Employe
public DateTime DateNaissance { get; set; } //Employe
public string Langue { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<Titre> Titres { get; set; } //TitreEmploye
public class Titre
{
public string description { get; set; } //TitreEmploye
}
//////////////////////////////////////////////////////////////
public IEnumerable<Departement> Departements { get; set; } //Departement
public class Departement
{
public string description { get; set; } //Departement
}
//////////////////////////////////////////////////////////////
public IEnumerable<Superviseur> Superviseurs { get; set; } //Employe
public class Superviseur
{
public string nomSuperviseur { get; set; } //Employe
}
public string StatutEmploye { get; set; } //Employe
public DateTime DateEmbauche { get; set; } //Employe
public Nullable<System.DateTime> DateDepart { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<Employeur> Employeurs { get; set; } //Employeur
public class Employeur
{
public string nomEmployeur { get; set; } //Employeur
}
//////////////////////////////////////////////////////////////
public IEnumerable<Localisation> Localisations { get; set; } //Localisation
public class Localisation
{
public string description { get; set; } //Localisation
}
public bool CarteAcces { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<TelephoneBureau> TelephoneBureaux { get; set; } //TelephoneBureau
public class TelephoneBureau
{
public string extension { get; set; } //TelephoneBureau
}
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllTelephoneCellulaires { get; set; } //TelephoneCellulaire
private List<int> _selectedTelephoneCellulaires;
public List<int> SelectedTelephoneCellulaires
{
get
{
if (_selectedTelephoneCellulaires == null)
{
_selectedTelephoneCellulaires = Employe.TelephoneCellulaire1.Select(m => m.IdTelephoneCellulaire).ToList();
}
return _selectedTelephoneCellulaires;
}
set { _selectedTelephoneCellulaires = value; }
}
public bool CarteAffaire { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllEquipementInformatiques { get; set; } //EquipementInfo
private List<int> _selectedEquipementInformatiques;
public List<int> SelectedEquipementInformatiques
{
get
{
if (_selectedEquipementInformatiques == null)
{
_selectedEquipementInformatiques = Employe.EquipementInfo.Select(m => m.IdEquipementInfo).ToList();
}
return _selectedEquipementInformatiques;
}
set { _selectedEquipementInformatiques = value; }
}
public string AdresseCourriel { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllGroupeSecurites { get; set; } //GroupeSecurite
private List<int> _selectedGroupeSecurites;
public List<int> SelectedGroupeSecurites
{
get
{
if (_selectedGroupeSecurites == null)
{
_selectedGroupeSecurites = Employe.GroupeSecurite1.Select(m => m.IdGroupeSecurite).ToList();
}
return _selectedGroupeSecurites;
}
set { _selectedGroupeSecurites = value; }
}
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllAccesApplicatifs { get; set; } //AccesApplicatif
private List<int> _selectedAccesApplicatifs;
public List<int> SelectedAccesApplicatifs
{
get
{
if (_selectedAccesApplicatifs == null)
{
_selectedAccesApplicatifs = Employe.AccesApplicatif1.Select(m => m.IdAccesApplicatif).ToList();
}
return _selectedAccesApplicatifs;
}
set { _selectedAccesApplicatifs = value; }
}
public bool CodeAlarme { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllCleBatiments { get; set; } //CleBatiment
private List<int> _selectedCleBatiments;
public List<int> SelectedCleBatiments
{
get
{
if (_selectedCleBatiments == null)
{
_selectedCleBatiments = Employe.CleBatiment1.Select(m => m.IdCleBatiment).ToList();
}
return _selectedCleBatiments;
}
set { _selectedCleBatiments = value; }
}
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllVehiculeCompagnies { get; set; } //VehiculeCompagnie
private List<int> _selectedVehiculeCompagnies;
public List<int> SelectedVehiculeCompagnies
{
get
{
if (_selectedVehiculeCompagnies == null)
{
_selectedVehiculeCompagnies = Employe.VehiculeCompagnie1.Select(m => m.IdVehiculeCompagnie).ToList();
}
return _selectedVehiculeCompagnies;
}
set { _selectedVehiculeCompagnies = value; }
}
public bool IsSuperviseur { get; set; } //Employe
public bool IsActif { get; set; } //Employe
public EmployeVM()
{
AllTelephoneCellulaires = new List<SelectListItem>();
AllEquipementInformatiques = new List<SelectListItem>();
AllGroupeSecurites = new List<SelectListItem>();
AllAccesApplicatifs = new List<SelectListItem>();
AllCleBatiments = new List<SelectListItem>();
AllVehiculeCompagnies = new List<SelectListItem>();
}
}
And here's the Create part of my Controller (I KNOW I will have to add some methods to comply to DRY, but for now, that's what it is:
// GET: Employes/Create
//[AcceptVerbs(HttpVerbs.Get), ImportModelStateFromTempData]
public ActionResult Create()
{
var employeView = new EmployeVM();
//Population pour les ListBoxFor
var allTelephoneCellulaireActifList = db.TelephoneCellulaireActif.ToList();
ViewBag.AllTelephoneCellulaires = allTelephoneCellulaireActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdTelephoneCellulaire.ToString()
});
var allEquipementInfoActifList = db.EquipementInfoActif.ToList();
ViewBag.AllEquipementInformatiques = allEquipementInfoActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdEquipementInfo.ToString()
});
var allGroupeSecuriteList = db.GroupeSecurite.ToList();
ViewBag.AllGroupeSecurites = allGroupeSecuriteList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdGroupeSecurite.ToString()
});
var allAccesApplicatifActifList = db.AccesApplicatifActif.ToList();
ViewBag.AllAccesApplicatifs = allAccesApplicatifActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdAccesApplicatif.ToString()
});
var allCleBatimentList = db.CleBatiment.ToList();
ViewBag.AllCleBatiments = allCleBatimentList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdCleBatiment.ToString()
});
var allVehiculeCompagnieActifList = db.VehiculeCompagnieActif.ToList();
ViewBag.AllVehiculeCompagnies = allVehiculeCompagnieActifList.Select(o => new SelectListItem
{
Text = o.DescriptionVehicule,
Value = o.IdVehiculeCompagnie.ToString()
});
//Zero-or-One-to-Many relationships
List<TitreEmployeActif> ListeTitreEmployeActif = db.TitreEmployeActif.OrderBy(titre => titre.Description).ToList();
ViewBag.IdTitre = new SelectList(ListeTitreEmployeActif, "IdTitre", "Description");
List<Departement> ListeDepartement = db.Departement.OrderBy(departement => departement.Description).ToList();
ViewBag.IdDepartement = new SelectList(ListeDepartement, "IdDepartement", "Description");
List<EmployeSuperviseurActif> ListeEmployeSuperviseurActif = db.EmployeSuperviseurActif.OrderBy(sup => sup.PrenomNom).ToList();
ViewBag.IdSuperviseur = new SelectList(ListeEmployeSuperviseurActif, "IdEmploye", "PrenomNom");
List<Employeur> ListeEmployeur = db.Employeur.OrderBy(employeur => employeur.NomEmployeur).ToList();
ViewBag.IdEmployeur = new SelectList(ListeEmployeur, "IdEmployeur", "NomEmployeur");
List<Localisation> ListeLocalisation = db.Localisation.OrderBy(localisation => localisation.Description).ToList();
ViewBag.IdLocalisation = new SelectList(ListeLocalisation, "IdLocalisation", "Description");
List<TelephoneBureauActif> ListeTelephoneBureauActif = db.TelephoneBureauActif.OrderBy(phone => phone.Extension).ToList();
ViewBag.IdTelephoneBureau = new SelectList(ListeTelephoneBureauActif, "IdTelephoneBureau", "Extension");
return View();
}
// POST: Employes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to,
// for more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(EmployeVM employeView)
{
if (!ModelState.IsValid)
{
foreach (var obj in ModelState.Values)
{
foreach (var error in obj.Errors)
{
if (!string.IsNullOrEmpty(error.ErrorMessage))
System.Diagnostics.Debug.WriteLine("ERROR WHY = " + error.ErrorMessage);
}
}
}
if (ModelState.IsValid)
{
var employeToAdd = db.Employe
.Include(e => e.TelephoneCellulaire1)
.Include(e => e.EquipementInfo)
.Include(e => e.GroupeSecurite1)
.Include(e => e.AccesApplicatif1)
.Include(e => e.CleBatiment1)
.Include(e => e.VehiculeCompagnie1)
.First();
if (TryUpdateModel(employeToAdd, "Employe", new string[] { "IdEmploye", "NomEmploye", "PrenomEmploye", "IdTitre", "IdDepartement", "IdSuperviseur", "DateEmbauche", "DateDepart", "StatutEmploye", "IdEmployeur", "IdLocalisation", "Langue", "CarteAcces", "TelephoneCellulaire", "IdTelephoneBureau", "CarteAffaire", "EquipementInformatique", "AdresseCourriel", "GroupeSecurite", "AccesApplicatif", "CodeAlarme", "CleBatiment", "VehiculeCompagnie", "DateNaissance", "IsSuperviseur", "IsActif" }))
{
var updatedTelephoneCellulaires = new HashSet<int>(employeView.SelectedTelephoneCellulaires);
var updatedEquipementInformatiques = new HashSet<int>(employeView.SelectedEquipementInformatiques);
var updatedGroupeSecurites = new HashSet<int>(employeView.SelectedGroupeSecurites);
var updatedAccesApplicatifs = new HashSet<int>(employeView.SelectedAccesApplicatifs);
var updatedCleBatiments = new HashSet<int>(employeView.SelectedCleBatiments);
var updatedVehiculeCompagnies = new HashSet<int>(employeView.SelectedVehiculeCompagnies);
//Prochaine ligne db.TelephoneCellulaire1 !!! ou db.TelephoneCellulaireActif ??? Check readonly
foreach (TelephoneCellulaire telephone in db.TelephoneCellulaire)
{
if (!updatedTelephoneCellulaires.Contains(telephone.IdTelephoneCellulaire))
{
employeToAdd.TelephoneCellulaire1.Remove(telephone);
}
else
{
employeToAdd.TelephoneCellulaire1.Add(telephone);
}
}
foreach (EquipementInfo equipement in db.EquipementInfo)
{
if (!updatedEquipementInformatiques.Contains(equipement.IdEquipementInfo))
{
employeToAdd.EquipementInfo.Remove(equipement);
}
else
{
employeToAdd.EquipementInfo.Add(equipement);
}
}
foreach (GroupeSecurite groupe in db.GroupeSecurite)
{
if (!updatedGroupeSecurites.Contains(groupe.IdGroupeSecurite))
{
employeToAdd.GroupeSecurite1.Remove(groupe);
}
else
{
employeToAdd.GroupeSecurite1.Add(groupe);
}
}
foreach (AccesApplicatif acces in db.AccesApplicatif)
{
if (!updatedAccesApplicatifs.Contains(acces.IdAccesApplicatif))
{
employeToAdd.AccesApplicatif1.Remove(acces);
}
else
{
employeToAdd.AccesApplicatif1.Add(acces);
}
}
foreach (CleBatiment cle in db.CleBatiment)
{
if (!updatedCleBatiments.Contains(cle.IdCleBatiment))
{
employeToAdd.CleBatiment1.Remove(cle);
}
else
{
employeToAdd.CleBatiment1.Add(cle);
}
}
foreach (VehiculeCompagnie vehicule in db.VehiculeCompagnie)
{
if (!updatedVehiculeCompagnies.Contains(vehicule.IdVehiculeCompagnie))
{
employeToAdd.VehiculeCompagnie1.Remove(vehicule);
}
else
{
employeToAdd.VehiculeCompagnie1.Add(vehicule);
}
}
}
db.Employe.Add(employeToAdd);
db.SaveChanges();
return RedirectToAction("Index");
}
var allTelephoneCellulaireActifList = db.TelephoneCellulaireActif.ToList();
ViewBag.AllTelephoneCellulaires = allTelephoneCellulaireActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdTelephoneCellulaire.ToString()
});
var allEquipementInfoActifList = db.EquipementInfoActif.ToList();
ViewBag.AllEquipementInformatiques = allEquipementInfoActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdEquipementInfo.ToString()
});
var allGroupeSecuriteList = db.GroupeSecurite.ToList();
ViewBag.AllGroupeSecurites = allGroupeSecuriteList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdGroupeSecurite.ToString()
});
var allAccesApplicatifActifList = db.AccesApplicatifActif.ToList();
ViewBag.AllAccesApplicatifs = allAccesApplicatifActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdAccesApplicatif.ToString()
});
var allCleBatimentList = db.CleBatiment.ToList();
ViewBag.AllCleBatiments = allCleBatimentList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdCleBatiment.ToString()
});
var allVehiculeCompagnieActifList = db.VehiculeCompagnieActif.ToList();
ViewBag.AllVehiculeCompagnies = allVehiculeCompagnieActifList.Select(o => new SelectListItem
{
Text = o.DescriptionVehicule,
Value = o.IdVehiculeCompagnie.ToString()
});
//Zero-or-One-to-Many relationships
List<TitreEmployeActif> ListeTitreEmployeActif = db.TitreEmployeActif.OrderBy(titre => titre.Description).ToList();
ViewBag.IdTitre = new SelectList(ListeTitreEmployeActif, "IdTitre", "Description");
List<Departement> ListeDepartement = db.Departement.OrderBy(departement => departement.Description).ToList();
ViewBag.IdDepartement = new SelectList(ListeDepartement, "IdDepartement", "Description");
List<EmployeSuperviseurActif> ListeEmployeSuperviseurActif = db.EmployeSuperviseurActif.OrderBy(sup => sup.PrenomNom).ToList();
ViewBag.IdSuperviseur = new SelectList(ListeEmployeSuperviseurActif, "IdEmploye", "PrenomNom");
List<Employeur> ListeEmployeur = db.Employeur.OrderBy(employeur => employeur.NomEmployeur).ToList();
ViewBag.IdEmployeur = new SelectList(ListeEmployeur, "IdEmployeur", "NomEmployeur");
List<Localisation> ListeLocalisation = db.Localisation.OrderBy(localisation => localisation.Description).ToList();
ViewBag.IdLocalisation = new SelectList(ListeLocalisation, "IdLocalisation", "Description");
List<TelephoneBureauActif> ListeTelephoneBureauActif = db.TelephoneBureauActif.OrderBy(phone => phone.Extension).ToList();
ViewBag.IdTelephoneBureau = new SelectList(ListeTelephoneBureauActif, "IdTelephoneBureau", "Extension");
return View(employeView);
}
And just to complete the picture, an extract from Create.cshtml:
<div class="form-group">
#Html.LabelFor(model => model.AllEquipementInformatiques, "Équipements informatiques", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ListBoxFor(model => model.SelectedEquipementInformatiques, (IEnumerable<SelectListItem>)ViewBag.AllEquipementInformatiques, new { #class = "form-control" })
</div>
</div>
Speaking about a picture, here's a little capture of one of my Many-to-Many table, with data entered with Edit:
Employe_VehiculeCompagnie
The thing to know (and I think it might be part of the problem) is: all of the 6 Many-To-Many relationships are optional. But even when I try to create a new Employe with at least one item in each of the 6 Many-to-Many field, it throws that error. And it still works in Edit. Questions: why this error is thrown and how can I make my app works? Any help would be greatly appreciated.
Edit:
Should I add this? One of my join table:
CREATE TABLE [dbo].[Employe_GroupeSecurite] (
[IdEmploye] INT NOT NULL,
[IdGroupeSecurite] INT NOT NULL,
PRIMARY KEY CLUSTERED ([IdEmploye] ASC, [IdGroupeSecurite] ASC),
CONSTRAINT [FK_Employe_GroupeSecurite_Employe] FOREIGN KEY ([IdEmploye]) REFERENCES [dbo].[Employe] ([IdEmploye]),
CONSTRAINT [FK_Employe_GroupeSecurite_GroupeSecurite] FOREIGN KEY ([IdGroupeSecurite]) REFERENCES [dbo].[GroupeSecurite] ([IdGroupeSecurite])
Now what?
I found it! Here's my solution, in case someone else tumbles with the same problem.
For some strange reason, Visual Studio added a '1' at the end of some of my Many-to-Many tables name. Entity Framework did not like it (neither did I), so I renamed them in my model:
Example:
public Employe()
{
this.AccesApplicatif1 = new HashSet<AccesApplicatif>();
this.TelephoneCellulaire1 = new HashSet<TelephoneCellulaire>();
this.CleBatiment1 = new HashSet<CleBatiment>();
this.EquipementInfo = new HashSet<EquipementInfo>();
this.GroupeSecurite1 = new HashSet<GroupeSecurite>();
this.VehiculeCompagnie1 = new HashSet<VehiculeCompagnie>();
this.Employe1 = new HashSet<Employe>();
}
Became:
this.AccesApplicatif = new HashSet<AccesApplicatif>();
this.TelephoneCellulaire = new HashSet<TelephoneCellulaire>();
this.CleBatiment = new HashSet<CleBatiment>();
this.EquipementInfo = new HashSet<EquipementInfo>();
this.GroupeSecurite = new HashSet<GroupeSecurite>();
this.VehiculeCompagnie = new HashSet<VehiculeCompagnie>();
this.Employe1 = new HashSet<Employe>();
Visual Studio was intelligent enough to rename them in pretty much everything, except in my Entities.edmx, Views and my Metadata. I took great care of it and now, verything work like a charm. I still don't understand why I was able to Edit my employes though...

MVC ASP.net Multiple Views trying to store tags

Model:
public class PublishedSongViewModel
{
public int Id { get; set; }
[Required(AllowEmptyStrings = false)]
public string SongName { get; set; }
//...
[Required]
public IEnumerable<string> Category { get; set; }
}
public class CategoryViewModel
{
public short Id { get; set; }
public string Title { get; set; }
public virtual ICollection<SongCategoryViewModel> SongCategory { get; set; }
}
public class SongCategoryViewModel
{
public int Id { get; set; }
[Required]
public int PublishedSongId { get; set; }
[Required]
public short CategoryId { get; set; }
}
View:
#model IList<PublishedSongViewModel>
#using (Html.BeginForm("PublishMusic", "Publish", FormMethod.Post, new { #enctype = "multipart/form-data", #id = "form-upload" }))
{
#Html.DropDownListFor(x => Model[i].Category, new SelectList(//Categories list here), new { #class = "form-control dl_Categories ", Multiple = "Multiple" })
}
Controller:
[HttpPost]
public ActionResult PublishMusic(IEnumerable<PublishedSongViewModel> songDetails)
{
if (songDetails != null)
{
IEnumerable<PublishedSongViewModel> savedSongs = (IEnumerable<PublishedSongViewModel>)(Session["UserSongs"]);
var lookupDetails = songDetails.ToDictionary(song => song.Id, song => song);
if (savedSongs != null)
{
foreach (var publishedSong in savedSongs)
{
var key = publishedSong.Id;
if (lookupDetails.ContainsKey(key))
{
var details = lookupDetails[key];
publishedSong.SongName = details.SongName;
}
db.SongCategories.Add(new SongCategoryViewModel { PublishedSongId = key, CategoryId = //categories id that user typed in on editorFor});
db.PublishedSongs.Add(publishedSong);
db.SaveChanges();
}
}
}
return View("Index");
}
I'v filled CategoryViewModel table up with data in my SQL.
1) How do I get the titles of CategoryViewModel and pass them in the SelectList(//Here) parameter in my viewmodel?
2) In the PublishMusic Action, how do I get the CategoryId for the SongCategoryViewModel from the one or more categories that the user selected from songDetails.Category?
I am not sure if I am on the right track with this. basically the categories are like tags, the user can select more than one. I'v also cut out unessential code to make easier to read.

The right way to bind the model to save multiple records to a table

I have a Menusettings pages which displays all the menuname from the database(Menutable).I want to save all the details into MenuRole table.For that I think I have to iterate over each menuitem and store the details in the MenuRole table(Is it the correct method?).But the problem is I am getting MenuList as null.So I couldnot iterate over the menulist .Also I am not sure how can i bind the checkbox value to the MenuRole table.
The view is
Model is
public class MenuRoleVM
{
public int? RoleId { get; set; }
public SelectList RoleList { get; set; }
public MenuRole MenuRole { get; set; }
public IEnumerable<Menu> MenuList { get; set; }
}
public partial class MenuRole
{
public int Id { get; set; }
public Nullable<int> MenuID { get; set; }
public Nullable<int> RoleID { get; set; }
public Nullable<System.DateTime> TransactionTime { get; set; }
public bool CanAdd { get; set; }
public bool CanEdit { get; set; }
public bool CanDelete { get; set; }
public bool CanView { get; set; }
public virtual Menu Menu { get; set; }
public virtual Role Role { get; set; }
}
public partial class Menu
{
public Menu()
{
this.MenuRoles = new HashSet<MenuRole>();
}
public int Id { get; set; }
public string MenuName { get; set; }
public string NavigateUrl { get; set; }
public Nullable<int> ParentID { get; set; }
public virtual ICollection<MenuRole> MenuRoles { get; set; }
}
Controller for binding the View
public ActionResult Add()
{
var _menuRoleVM = new MenuRoleVM
{
RoleList = new SelectList(_db.Roles.ToList(), "Id", "RoleName"),
MenuList = _db.Menus.Where(m => m.NavigateUrl != "#"),
MenuRole = new MenuRole()
};
return View(_menuRoleVM);
}
HTML Markup of View
#model SMS.Models.ViewModel.MenuRoleVM
#foreach (var item in Model.MenuList.Select((x, i) => new { Data = x, Index = i }))
{
<tr>
<td>
<input type="checkbox" class="minimal checkAll" />
</td>
<td>#item.Data.MenuName</td>
<td>
#Html.CheckBoxFor(m => m.MenuRole.CanAdd, new { #class = "minimal single" })
</td>
<td>
#Html.CheckBoxFor(m => m.MenuRole.CanEdit, new { #class = "minimal single" })
</td>
<td>
#Html.CheckBoxFor(m => m.MenuRole.CanDelete, new { #class = "minimal single" })
</td>
<td>
#Html.CheckBoxFor(m => m.MenuRole.CanView, new { #class = "minimal single" })
</td>
</tr>
}
Any help is highly appreciated?
You need view models that represent what you want to display/edit
public class MenuVM
{
public int ID { get; set; }
public string Name { get; set; }
public bool CanAdd { get; set; }
public bool CanEdit { get; set; }
public bool CanDelete { get; set; }
public bool CanView { get; set; }
}
public class MenuRoleVM
{
public int? RoleId { get; set; }
public SelectList RoleList { get; set; }
public List<MenuVM> MenuList { get; set; }
}
and in the view
#model MenuRoleVM
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.RoleId, Model.RoleList)
for(int i = 0; i < Model.MenuList.Count; i++)
{
#Html.HiddenFor(m => m.MenuList[i].ID)
#Html.DisplayFor(m => m.MenuList[i].Name)
#Html.CheckBoxFor(m => m.MenuList[i].CanAdd)
#Html.CheckBoxFor(m => m.MenuList[i].CanEdit)
....
}
<input type="submit" ... />
}

Kendo grid image column

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

Resources