how to get data from multiple model in mvc4? - asp.net-mvc-3

I've a problem in customize view in my application that upload images
i have three models
public int EmpId { get; set; }
public string EmployeeName { get; set; }
public virtual ICollection<Picture> picture{ get; set; }
and second
public int MacId { get; set; }
public string machine { get; set; }
and third
public int PicId { get; set; }
public string PicPath { get; set; }
public int MacId { get; set; }
public int EmpId { get; set; }
public virtual Employee Employee { get; set; }
and i want to make it show picture of mac and who is the employee who take it ?

Create New Model With the neccesary properties you want to bind to your view.
for eg:
class newModelName
{
public Model1TypeName model1 {get ; set; }
public Model2TypeName model2 {get ; set; }
public Model3TypeName model3 {get ; set; }
}
Now you can bind this new model to your view which will have all necessary information from all the three views.

Related

Passing more than one model to the view in ASP.NET MVC

I need to pass two models in the same view, however some elements have the same name.
I have two models Employee and HolidayRequestForm and I need to use both of these in the one view which will be a details page for each Employee.
Here is my Employee:
public partial class Employee
{
public int EmployeeID { get; set; }
public string FullName { get; set; }
public string EmailID { get; set; }
public string Password { get; set; }
public System.DateTime StartDate { get; set; }
public int RoleID { get; set; }
public int ShiftID { get; set; }
public int AreaID { get; set; }
public int DisciplineID { get; set; }
public int SiteID { get; set; }
public int ALCategory { get; set; }
public Nullable<int> HoursTaken { get; set; }
public Nullable<int> AwardedLeave { get; set; }
public Nullable<int> TotalHoursThisYear { get; set; }
public int HoursCarriedForward { get; set; }
public Nullable<int> EntitlementRemainingThisYear { get; set; }
public string Comments { get; set; }
}
Here is my HolidayRequestForm:
public partial class HolidayRequestForm
{
public int RequestID { get; set; }
public int EmployeeID { get; set; }
public System.DateTime StartDate { get; set; }
public System.DateTime FinishDate { get; set; }
public int HoursTaken { get; set; }
public string Comments { get; set; }
public int YearCreated { get; set; }
public int MonthCreated { get; set; }
public Nullable<int> DayCreated { get; set; }
public Nullable<int> YearOfHoliday { get; set; }
}
I have tried Creating a separate model that contains all elements to use in the view but I'm not sure how to differentiate elements with the same name eg. Comments Is it even possible to do so?
I would like to use both these models in my view as I'd like to create an Employee Profile page, with their info on the top displaying information about their profile and then holidays they have requested using the holidayrequestform in a table on the bottom of the page.
Write a ViewModel which will contain both Employee and HolidayRequestForm as follows and then pass the ViewModel to the view:
public class EmployeeViewModel
{
public Employee Employee {get; set;}
public HolidayRequestForm HolidayRequestForm {get; set;}
}
Then in your action method:
public ActionResult EmployeeDetails(int id)
{
Employee employee = _dbContext.Employees.FirstOrDefault(emp => emp.EmployeeID == id);
HolidayRequestForm holidayRequestForm = _dbContext.HolidayRequestForms.FirstOrDefault(hrf => hrf.EmployeeID == id);
EmployeeViewModel employeeViewModel = new EmployeeViewModel()
{
Employee = employee,
HolidayRequestForm = holidayRequestForm
}
return View(employeeViewModel);
}
Then in the view, access the model properties as follows:
#model EmployeeViewModel
<p>Full Name: #Model.Employee.FullName</p>

Entity Framework not binding entity

I have the following db structure:
I am using EF6 to create the entities from database and have the following classes created by EF6:
public partial class Mechanic
{
public Mechanic()
{
this.MechanicAddresses = new HashSet<MechanicAddress>();
this.MechanicServices = new HashSet<MechanicService>();
}
public string ID { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public Nullable<System.DateTime> LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public string UserName { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string MobileNumber { get; set; }
public Nullable<bool> IsMobile { get; set; }
public string Url { get; set; }
public string FaceBookUrl { get; set; }
public string TwitterUrl { get; set; }
public string Description { get; set; }
public string Discriminator { get; set; }
public bool IsEnabled { get; set; }
public bool IsAuthorised { get; set; }
public string Logo { get; set; }
public System.DateTime CreationTimestamp { get; set; }
public virtual ICollection<MechanicAddress> MechanicAddresses { get; set; }
public virtual ICollection<MechanicService> MechanicServices { get; set; }
}
public partial class MechanicAddress
{
public int ID { get; set; }
public string MechanicId { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string District { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public int CountryId { get; set; }
public System.DateTime CreationTimestamp { get; set; }
public bool IsPrimary { get; set; }
public Nullable<double> Latitude { get; set; }
public Nullable<double> Longitude { get; set; }
public System.Data.Entity.Spatial.DbGeography Location { get; set; }
public virtual Country Country { get; set; }
public virtual Mechanic Mechanic { get; set; }
}
public partial class MechanicService
{
public int ID { get; set; }
public string MechanicId { get; set; }
public string Service { get; set; }
public virtual Mechanic Mechanic { get; set; }
}
The data is correct so i expect to get data in all entities.
When i run the following linq query in my DAL:
Mechanic mech = context.Mechanics.Where(a => a.ID == id).Include(a => a.MechanicAddresses).Include(a => a.MechanicServices).FirstOrDefault();
It returns the mechanic and mechanicAddresses but mechanicServices is always empty (count == 0).
When i run the same query in LinqPad I get all entities filled as expected.
I have removed the edmx and re-created it but still get the same issue.
Please check if "MultipleActiveResultSets" is set to true and LazyLoadingEnabled is enabled in connection string. It may help.
And what about your OnModelCreating?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
It's not necessary to use Include if you have LazyLoading (virtual). And If it works fine in LinqPad try to do migration into empty DB (just test). And then try to get data from test DB.
The only way i was able to resolve this was to:
delete the EDMX
script the create for the mechanicsServices table
script the data
drop the mechanicsServices table
run the create table script from above
run the insert data script
regenerate the EDMX
This now works, WTF! Can't explain it.
I know it's always best to understand what went wrong but this one beat me.
I had same problem.
If you using git, please check .edmx file old version. SSDL content may be missing.

How to use the mvc 3 dropdownlist

Hello I'm new to mvc 3 and I need some pointers/help populating a dropdownlist. I have 3 classes which are my domain classes. Basically what I want to do is make a dropdownlist that will be populated with a specific members rented movies. What is the easiest way to do this? Is it to use the ViewBag or to make a ViewModel?
public class Member
{
public virtual int MemberId { get; set; }
public virtual long PersonalNr { get; set; }
public virtual string Name { get; set; }
public virtual string LastName { get; set; }
public virtual List<Rental> Rentals { get; set; }
}
public class Movie
{
public virtual int MovieId { get; set; }
public virtual string Name { get; set; }
public virtual bool IsInStock { get; set; }
}
public class Rental
{
public virtual int RentalId { get; set; }
public virtual int MovieId { get; set; }
public virtual Movie Movie { get; set; }
public virtual int MemberId { get; set; }
public virtual Member Member { get; set; }
public DateTime startDate { get; set; }
public DateTime dueDate { get; set; }
}
The easiest way is
#Html.DropDownListFor(
x => x.SelectedRentalId,
Model.Rentals
)
to know a little better on how to use it, including the select part, se Darin's answer
https://stackoverflow.com/a/6807331/28004

Code-First Referencing Table

I am currently struggling with some mapping properties on my models. Here are my two models.
What I am looking to do is only have unique PersonTypes (ie MD, Nurse) in my table and the person model reference these personTypes.
public partial class Person
{
public Person()
{
this.PersonTypes = new List<PersonType>();
this.Contacts = new List<Contact>();
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int FacilityId { get; set; }
[DataType(DataType.Text), MaxLength(200), Required]
public string FirstName { get; set; }
[DataType(DataType.Text), MaxLength(200)]
public string MiddleName { get; set; }
[DataType(DataType.Text), MaxLength(200), Required]
public string LastName { get; set; }
public int? SpecialtyId { get; set; }
public bool IsEnabled { get; set; }
// Mapped Properties
[ForeignKey("FacilityId")]
public virtual Facility Facility { get; set; }
[ForeignKey("SpecialtyId")]
public virtual Specialty Specialty { get; set; }
public virtual ICollection<PersonType> PersonTypes { get; set; }
public virtual ICollection<Contact> Contacts { get; set; }
}
public partial class PersonType
{
public PersonType()
{
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[DataType(DataType.Text), MaxLength(200), Required]
public string Name { get; set; }
public bool IsEnabled { get; set; }
}
Person1 = MD, Nurse - Person2 = MD - Person3 = Nurse, CNP
I don't want to have MD in my PersonType Table 2 times from above example. Is this possible. Thanks.
From your example I gather that you have many-to-many relationship between Persons and PersonTypes. For EF CodeFirst to understand this you have to create symmetric navigation property in you PersonType: public virtual ICollection<Person> Persons.

Relationships between tables mvc3

I'm building website in MVC 3.
i am using EF code first in existing database.
my ET inside the model look like that:
public class Pages
{
[Required]
public int ID { get; set; }
public int ParentID { get; set; }
[Required]
public int PageType { get; set; }
[Required]
[DataType(DataType.Text)]
[DisplayName("כותרת")]
public string Title { get; set; }
public string SearchWords { get; set; }
public string Leng { get; set; }
public int? Sort { get; set; }
public string Modules { get; set; }
[ForeignKey("PageType")]
public virtual PagesType Type { get; set; }
public virtual IEnumerable<PagesType> Types { get; set; }
[ForeignKey("PageID")]
public ICollection<PageContent> PageContent { get; set; }
[ForeignKey("PageID")]
public virtual ICollection<ImagesTable> Images { get; set; }
}
public class PageContent
{
public int ID { get; set; }
public int PageID { get; set; }
public string Header { get; set; }
public string Text { get; set; }
[ForeignKey("ID")]
public virtual ICollection<Pages> Pages { get; set; }
}
as you see in my fist table that cold Pages i have a relationship to another table that named PageContent.
in my Pages class i had this code
[ForeignKey("PageID")]
public ICollection<PageContent> PageContent { get; set; }
now, when i trying to add new pageContent into new page i get an error.
see this code
public ActionResult AddPage(PageModel page)
{
SystemLogic cmd = new SystemLogic();
page.Leng = "he";
Models.Pages p = new Pages();
p.ParentID = page.ParentID;
PageContent pageContent = new PageContent();
pageContent.Text = page.Content;
p.PageContent.Add(pageContent);
The error is
Object reference not set to an instance of an object.
What i did wrong?
You will get the NRE at p.PageContent.Add(pageContent); because the collection is not initialized. Initialize the collections inside the constructor of Pages class.
public class Pages
{
public Pages()
{
PageContent = List<PageContent>();
Images = List<ImagesTable>();
}
[Required]
public int ID { get; set; }
public int ParentID { get; set; }
[Required]
public int PageType { get; set; }
[Required]
[DataType(DataType.Text)]
[DisplayName("כותרת")]
public string Title { get; set; }
public string SearchWords { get; set; }
public string Leng { get; set; }
public int? Sort { get; set; }
public string Modules { get; set; }
[ForeignKey("PageType")]
public virtual PagesType Type { get; set; }
public virtual IEnumerable<PagesType> Types { get; set; }
[ForeignKey("PageID")]
public ICollection<PageContent> PageContent { get; set; }
[ForeignKey("PageID")]
public virtual ICollection<ImagesTable> Images { get; set; }
}
Or before you add objects to the collection
if (p.PageContent == null) p.PageContent = new List<PageContent>();
p.PageContent.Add(pageContent);
You should consider using proper naming conventions(eg Page instead of Pages).

Resources