Asp mvc 5 relationship many-to-many - asp.net-mvc

How to display all of the materials in the table Material on the page, as well as a number of related data from the Teacher table?
How do I best remake?
Here I describe the models
Models:
public class Teacher
{
public int TeacherId { get; set; }
public string TeacherName { get; set; }
public virtual ICollection<Material> Materials { get; set; }
public Teacher()
{
Materials = new List<Material>();
}
}
public class Material
{
public int MaterialId { get; set; }
public string MaterialName { get; set; }
public string MaterialDescription { get; set; }
public virtual ICollection<Teacher> Teachers { get; set; }
public Material()
{
Teachers = new List<Teacher>();
}
}
The connection to the database
EfdbContext
public class EfDbContext : DbContext
{
// For Science Controller
public DbSet<Teacher> Teachers { get; set; }
public DbSet<Material> Materials { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Teacher>().HasMany(c => c.Materials)
.WithMany(s => s.Teachers)
.Map(t => t.MapLeftKey("TeacherId")
.MapRightKey("MaterialId")
.ToTable("TeacherMaterials"));
}
}
Controller:
public class ScienceController : Controller
{
EfDbContext context = new EfDbContext();
// GET: Science
public ActionResult ScienceResult()
{
IQueryable<Material> materials = context.Materials.Include(p => p.Teachers);
IQueryable<Teacher> teachers = context.Teachers.Include(p => p.Materials);
MateriaLTeacherListView materiaLTeacher = new MateriaLTeacherListView()
{
Materials = materials.ToList(),
Teachers = teachers.ToList()
};
return View(materiaLTeacher);
}
}
View:
#using Diploma.Domain.Entities
#model Diploma.WebUI.Models.MateriaLTeacherListView
#{
ViewBag.Title = "ScienceResult";
}
<div>
#foreach (var p in Model.Materials)
{
<p>#p.MaterialDescription</p>
foreach (Teacher t in Model.Teachers)
{
<li>#t.TeacherName</li>
}
}
</div>

this might work:
#foreach (var p in Model.Materials)
{
<p>#p.MaterialDescription</p>
foreach (Teacher t in p.Teachers)
{
<li>#t.TeacherName</li>
}
}

Related

How to get data from another table(join) to DropDownListFor in MVC with SQL Server using entity framework

I'm working on a project ASP.NET MVC.I want to get data from SQL to #Html.DropDownListFor.
I get this NullReferenceException:
System.Web.Mvc.WebViewPage<TModel>.Model.get returned null.
I've been looking through this exception detail but can't figure what's causing this exception.
My view
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-list-alt"></i></span>
#Html.DropDownListFor(model => model.ID_Famille, new SelectList(Model.listfamille, "ID_Famille", "Nom_Famille"), "Select", new { #class = "form-control" })
</div>
</div>
My model
public partial class Article
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Article()
{
this.Details_Commande = new HashSet<Details_Commande>();
}
public int ID_Article { get; set; }
public string Nom_Article { get; set; }
public int Quantite_Article { get; set; }
public string Prix_Article { get; set; }
public int ID_Famille { get; set; }
public int Alert_Article { get; set; }
public int ID_Fournisseur { get; set; }
//public virtual Famille Famille { get; set; }
public virtual Fournisseur Fournisseur { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Details_Commande> Details_Commande { get; set; }
public List<Famille> listfamille { get; set; }
}
My Controller
public ActionResult getdata()
{
Article article = new Article();
article.listfamille = ob.Famille
.Select(tc => new Famille
{
ID_Famille = tc.ID_Famille,
Nom_Famille = tc.Nom_Famille
})
.ToList();
return View(article);
}
I've done my best to replicate your scenario/error but have been unable to. Here is what I did. If I've made any incorrect assumptions perhaps you could let me know and I will edit my answer. The code below generates a dropdown without a problem.
Note I don't recommend sending entity framework models to the view. I would normally use a view model. This looks like a good tutorial if you don't know what they are.
My models
public class Famille
{
public int ID_Famille { get; set; }
public string Nom_Famille { get; set; }
}
public class Article
{
public Article()
{
}
public int ID_Article { get; set; }
public string Nom_Article { get; set; }
public int Quantite_Article { get; set; }
public string Prix_Article { get; set; }
public int ID_Famille { get; set; }
public int Alert_Article { get; set; }
public int ID_Fournisseur { get; set; }
public List<Famille> listfamille { get; set; }
}
My Entity Framework 6.2 DbContext
public class MyContext: DbContext
{
public DbSet<Famille> Famille { get; set; }
public MyContext()
:base("{my connection string}")
{
Database.SetInitializer<MyContext>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Famille>()
.HasKey(c => c.ID_Famille);
modelBuilder.Entity<Famille>()
.ToTable("famille");
base.OnModelCreating(modelBuilder);
}
}
My controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult getdata()
{
using (var ob = new MyContext())
{
Article article = new Article();
var familles = ob.Famille.ToList();
article.listfamille = familles;
return View(article);
}
}
}
getData.cshtml
#using Article.Controllers
#model Article
#{
Layout = null;
}
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-list-alt"></i></span>
#Html.DropDownListFor(model => model.ID_Famille, new SelectList(Model.listfamille, "ID_Famille", "Nom_Famille"), "Select", new { #class = "form-control" })
</div>
</div>

How to Insert checkbox checked values id in Many to Many relationship table?

I wanted to add the value of checkbox ids to many to many relation table between two tables Course-Student
i have 3 tables Course{ CourseID,CourseName }, Studdent{StudentID,StudentName} and CourseStudet{CourseID, StudentID}
Course table already have course{1.DataScience,2.English,3.Physics}
while Inserting Student i have shown course checkboxes with these options fetching list of these courses from database to show in view to user when he is about to register now i am confused how to insert into database?
public class CourseModel {
public List<Course> mycourse{ get; set; }
public string StudentName {get; set;}
}
EF generated Class
public partial class Course
{
public Course()
{
this.Student= new HashSet<Student>();
}
public int CourseID { get; set; }
public string CourseName { get; set; }
i have inserted this field to check for checked value
public bool Ischecked { get; set; }
public virtual ICollection<Student> Student { get; set; }
}
public partial class Student
{
public Student()
{
this.Course= new HashSet<Course>();
}
public int StudentID { get; set; }
public string StudentName { get; set; }
public virtual ICollection<Course> Course{ get; set; }
}
public ActionResult Index()
{
CourseModel coursemodel = new CourseModel();
using (Entities db = new Entities())
{
coursemodel.mycourse = db.Course.ToList<Course>();
return View(coursemodel);
}
}
[HttpPost]
public ActionResult Index(CourseModel course)
{
return View(course);
}
View
#using (Html.BeginForm("index", "Course", FormMethod.Post))
<input type="Text" name="StudentName" placeholder="Name" />
{
<table>
#for (int i = 0 ; i < Model.mycourse.Count; i++)
{
if (i % 3 == 0) {
#:<tr></tr>
}
<div>
#Html.CheckBoxFor(x => x.mycourse[i].Ischecked)
<label>#Model.mycourse[i].CourseName</label>
#Html.HiddenFor(x => x.mycourse[i].CourseID)
#Html.HiddenFor(x => x.mycourse[i].CourseName)
</div>
}
</table>
<input type="submit" value="Submit" />
}
i am getting checkbox id,name and which course is checked now how can i add student with including these values to relationship table CourseStudent ?
You have problems with your database design. Remove ischecked field.Remember while you are designing entities, you shouldn't put fields that are for view. It is like that I make Reports table from my each query.
correct your models
public partial class Course
{
public Course()
{
this.Student = new HashSet<Student>();
}
public int CourseID { get; set; }
public string CourseName { get; set; }
public virtual ICollection<Student> Student { get; set; }
}
public partial class Student
{
public Student()
{
this.Course = new HashSet<Course>();
}
public int StudentID { get; set; }
public string StudentName { get; set; }
public virtual ICollection<Course> Course { get; set; }
}
Add viewmodels(You can use view models for showing custom data for your view)
You can read more
ViewModel
public class CourseViewModel
{
public Course course { get; set; }
public bool CheckBox { get; set; }
}
public class StudentCourseViewModel
{
public List<CourseViewModel> coursesVM { get; set; }
public Student student { get; set; }
}
Controller
public ActionResult index()
{
Entities db = new Entities();
List<CourseViewModel> courselist = new List<CourseViewModel>();
foreach (var item in db.Course.ToList())
{
courselist.Add(new CourseViewModel { course = item});
}
StudentCourceViewModel model = new StudentCourseViewModel(
{
student = new student(),
coursesVM = courselist }
};
return View(model);
}
[HttpPost]
public ActionResult Save(StudentCourseViewModel model)
{
Entities db = new Entities();
Student stdindb = db.Students.FirstorDefault(c => c.StudentName == model.student.StudentName);
if(stdindb == null)
{
stdindb = new student(){//your properties};
db.students.add(stdindb);
}
foreach (var item in model.coursesVM)
{
if (item.Ischecked)
{
stdindb.Course.Add(db.course.single(c=>c.CourseId == item.course.CourseId ));
}
}
db.SaveChanges();
return View();
}
View
#model SchoolCMS.Models.StudentCourseViewModel
#{
ViewBag.Title = "Select Course";
}
#using (Html.BeginForm("Save", "home", FormMethod.Post))
{
#Html.TextBoxFor(c=>c.student.StudentName)
<table>
#for (int i = 0; i < Model.coursesVM.Count; i++)
{
<tr>
<td>
#Html.CheckBoxFor(c => c.coursesVM[i].Ischecked)
#Html.HiddenFor(c => c.coursesVM[i].course.CourseID)
</td>
<td>#Html.DisplayFor(c => c.coursesVM[i].course.CourseName)</td>
</tr>
}
</table>
<input type="submit" value="Submit" />
}

how to access elements of a list in controller

Entities
public class Employee
{
public long BusinessUnitID{ get; set; }
public long EmployeeID { get; set; }
public long InfoTypeID { get; set; }
public string EmployeeName { get; set; }
public List<ContactData> ContactDetails{ get; set; }
}
public class ContactData
{
public string ContactTypeName { get; set; }
public string ContactValue { get; set; }
}
Model
Public class EmployeeDetails
{
public long BusinessUnitID { get; set; }
public List<EmployeeData> EmployeeInfo { get; set;}
public List<ContactInfo> Contacts { get; set; }
}
public class EmployeeData
{
public long EmployeeID { get; set;}
public string EmployeeName { get; set;}
}
Public class ContactInfo
{
public string ContactName { get; set; }
public long ContactValue { get; set; }
}
Controller
public ActionResult Update(long BusinessUnitID=2)
{
if (Session[Constants.Session_IsAdmin] != null && Convert.ToBoolean(Session[Constants.Session_IsAdmin]))
{
EmployeeDetails employeeDetails = new EmployeeDetails();
List<Employee> employee = GetEmployeeById(Convert.ToInt64(BusinessUnitID));
List<EmployeeData> lstEmployeeData = new List<EmployeeData>();
List<ContactInfo> lstContactInfo = new List<OptionDetails>();
var ID = employee.Select(x => x.BusinessUnitID).ToList();
foreach(var item in employee.Where(x => x.BusinessUnitID == BusinessUnitID))
{
EmployeeData employeeData = new EmployeeData();
employeeData.EmployeeID = item.EmployeeID;
employeeData.EmployeeName = item.EmployeeName;
foreach (var local in employee.Where(q => q.EmployeeID == employeeData.EmployeeID))
{
//ContactInfo contactInfo = new ContactInfo();
//contactInfo.ContactName = local.ContactDetails.Select(p => p.ContactName).ToString();
//contactInfo.ContactValue = local.ContactDetails.Select(s => s.ContactValue).ToString();
}
lstEmployeeData.Add(employeeData);
}
return View(EmployeeDetails);
}
else
{
return RedirectToAction("Login");
}
}
Here I'm getting a list Employee in which i have below properties and a list ContactDetails which is a list containing atleast 3 elements for its properties. For eg 3 types of ContactTypeName and ContactValue as Home: 000000000, work: 9999999, mobile: 8888888. For a businessUnitid i got all employeeid for a perticular EmployeeID i want contact details but i'm unable to get or 3 contactvalue and contactname. In list Employee there is list ContactDetails in which there would be 3 or 5 contact numbers. I don't know how must i assign it to a list.
As employee can have multiple contact details, you need to add contact detail list property to EmployeeData class
Model classes :
Public class EmployeeDetails
{
public EmployeeDetails()
{
EmployeeInfo = new List<EmployeeData>();
}
public long BusinessUnitID { get; set; }
public List<EmployeeData> EmployeeInfo { get; set;}
}
public class EmployeeData
{
public EmployeeData()
{
Contacts = new List<ContactInfo>();
}
public long EmployeeID { get; set;}
public string EmployeeName { get; set;}
public List<ContactInfo> Contacts { get; set; }
}
Public class ContactInfo
{
public string ContactName { get; set; }
public long ContactValue { get; set; }
}
Then it's easy to pass the data of employees with multiple contacts
public ActionResult Update(long BusinessUnitID=2)
{
if (Session[Constants.Session_IsAdmin] != null && Convert.ToBoolean(Session[Constants.Session_IsAdmin]))
{
List<Employee> employees = GetEmployeeById(Convert.ToInt64(BusinessUnitID));
List<EmployeeData> lstEmployeeData = new List<EmployeeData>();
foreach(var item in employee.Where(x => x.BusinessUnitID == BusinessUnitID))
{
EmployeeData employeeData = new EmployeeData();
employeeData.EmployeeID = item.EmployeeID;
employeeData.EmployeeName = item.EmployeeName;
foreach (var contact in employee.ContactDetails)
{
ContactInfo contactInfo = new ContactInfo();
contactInfo.ContactName = contact.ContactName;
contactInfo.ContactValue = contact.ContactValue;
employeeData.Contacts.Add(contactInfo);
}
lstEmployeeData.Add(employeeData);
}
EmployeeDetails empDetails = new EmployeeDetails();
empDetails.EmployeeInfo = lstEmployeeData;
return View(empDetails);
}
else
{
return RedirectToAction("Login");
}
}

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

DB initializer does not work with CreateDatabaseIfNotExists works will all other types

As the title says for some reason my database is not being created when specifying CreateDatabaseIfNotExists works fine with drop always and drop if model changes. The database is not created I get an error when in my view because the data is empty.
DBContext
public class SchemaDBContext : DbContext
{
public SchemaDBContext()
{
Database.SetInitializer(new SchemaDBInitializer());
}
public DbSet<UserRole> UserRoles { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<SalesStaff> SalesStaffs { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<CreditCard> CreditCards { get; set; }
public DbSet<Enquiry> Enquiries { get; set; }
public DbSet<Trip> Trips { get; set; }
public DbSet<TripImage> TripImages { get; set; }
public DbSet<Coach> Coaches { get; set; }
public DbSet<Ticket> Tickets { get; set; }
public DbSet<Review> Reviews { get; set; }
public DbSet<CartItem> CartItems { get; set; }
public DbSet<ShoppingCart> ShoppingCarts { get; set; }
public DbSet<OrderItem> OrderItems { get; set; }
public DbSet<Order> Orders { get; set; }
}
Initializer
public class SchemaDBInitializer : CreateDatabaseIfNotExists<SchemaDBContext>
{
protected override void Seed(SchemaDBContext context)
{
var customers = generateCustomers();
customers.ForEach(s => s.ShoppingCart = new ShoppingCart());
customers.ForEach(s => context.Customers.Add(s));
context.SaveChanges();
var salesStaffs = generateSalesStaffs();
salesStaffs.ForEach(s => context.SalesStaffs.Add(s));
context.SaveChanges();
var customerUsers = customers.Select(u => u.User).ToList();
var salesStaffUsers = salesStaffs.Select(u => u.User).ToList();
var userRoles = new List<UserRole>
{
new UserRole()
{
Role = "Customer",
Users = customerUsers
},
new UserRole()
{
Role = "SalesStaff",
Users = salesStaffUsers
}
};
userRoles.ForEach(s => context.UserRoles.Add(s));
context.SaveChanges();
var trips = generateTrips();
trips.ForEach(s => context.Trips.Add(s));
context.SaveChanges();
var tickets = generateTickets(customers, trips);
tickets.ForEach(s => context.Tickets.Add(s));
context.SaveChanges();
var reviews = generateReviews(customers, trips);
reviews.ForEach(s => context.Reviews.Add(s));
context.SaveChanges();
var enquiries = generatEnquiries(customers, salesStaffs);
enquiries.ForEach(s => context.Enquiries.Add(s));
context.SaveChanges();
var orders = generateOrders(customers);
orders.ForEach(order => context.Orders.Add(order));
context.SaveChanges();
}
}
The seed method is not being called by initializer.

Resources