how to access elements of a list in controller - asp.net-mvc

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

Related

How to fix view model for partial view

I've problem with creating new record to empty tables on SQLServer
When trying to pass new record I get 'Object reference not set to an instance of an object.' error
When I try edit existing record, tables display content properly, but save changes won't work. With Guests table it will only reload old entry without changes, and for Contacts it's returning same error as on creating new record.
App should let create and edit record by displaying as partial view editor forms for each table.
I'm beginner in MVC.
Below is my code.
Tables models:
[Table("GuestsTest")]
public class Guest
{
[Key]
[HiddenInput(DisplayValue = false)]
public int GuestID { get; set; }
public string GuestLastName { get; set; }
public string GuestFirstName { get; set; }
public string GuestMiddleName { get; set; }
public string GuestEmail { get; set; }
public string GuestSex { get; set; }
}
[Table("ContactsTest")]
public class Contact
{
[Key]
[HiddenInput(DisplayValue = false)]
public int ContactID { get; set; }
[HiddenInput(DisplayValue = false)]
public int GuestID { get; set; }
public int PostalCode { get; set; }
public string City { get; set; }
public string Street { get; set; }
public string HouseNumber { get; set; }
public string PhoneNumber { get; set; }
My view model
public class TableViewModel
{
public Guest GetGuest { get; set; }
public Contact GetContact { get; set; }
}
My controllers
public class AdminController : Controller
{
private IGuestRepository guestRepository;
private IContactRepository contactRepository;
private IQRCodeRepository qrcodeRepository;
public AdminController(IGuestRepository repoG, IContactRepository repoC, IQRCodeRepository repoQ)
{
guestRepository = repoG;
contactRepository = repoC;
qrcodeRepository = repoQ;
}
public ActionResult Index()
{
return View(guestRepository.Guests);
}
public ActionResult EditGuest(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TableViewModel viewModel = new TableViewModel();
viewModel.GetGuest = guestRepository.Guests.FirstOrDefault(g => g.GuestID == id);
viewModel.GetContact = contactRepository.Contacts.FirstOrDefault(c => c.ContactID == id);
if (viewModel.GetGuest == null)
{
return HttpNotFound();
}
return View(viewModel);
}
public ActionResult GuestForm(int? id)
{
var viewModel = new TableViewModel();
viewModel.GetGuest = guestRepository.Guests.FirstOrDefault(g => g.GuestID == id);
return PartialView("_GuestForm", viewModel.GetGuest);
}
[HttpPost]
public ActionResult GuestForm(TableViewModel getGuest)
{
if (ModelState.IsValid)
{
guestRepository.SaveGuest(getGuest.GetGuest);
qrcodeRepository.CreateQRCode(getGuest.GetGuest);
TempData["message"] = string.Format("Zapisano {0} {1}", getGuest.GetGuest.GuestFirstName, getGuest.GetGuest.GuestLastName);
return RedirectToAction("EditGuest/" + getGuest.GetGuest.GuestID);
}
else
{
return PartialView(getGuest.GetGuest);
}
}
public ActionResult ContactForm(int? id)
{
var viewModel = new TableViewModel();
viewModel.GetContact = contactRepository.Contacts.FirstOrDefault(c => c.ContactID == id);
return PartialView("_ContactForm", viewModel.GetContact);
}
[HttpPost]
public ActionResult ContactForm(TableViewModel getGuest)
{
if (ModelState.IsValid)
{
contactRepository.SaveContact(getGuest.GetContact);
TempData["message"] = string.Format("Zapisano {0} {1}", getGuest.GetGuest.GuestFirstName, getGuest.GetGuest.GuestLastName);
return RedirectToAction("EditGuest/" + getGuest.GetGuest.GuestID);
}
else
{
return PartialView(getGuest.GetContact);
}
}
public ActionResult Create()
{
return View("EditGuest", new TableViewModel());
}
My view
#model MSConference.WebUI.Models.TableViewModel
#{
if (Model.GetGuest.GuestEmail == null)
{
ViewBag.Title = "Tworzenie nowego użytkownika";
}
else
{
ViewBag.Title = "Edycja";
}
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
#if (Model.GetGuest.GuestEmail == null)
{
<h2>Tworzenie nowego użytkownika</h2>
}
else
{
<h2>Edycja - #Model.GetGuest.GuestFirstName #Model.GetGuest.GuestLastName</h2>
}
#using (Html.BeginForm("EditGuest", "Admin"))
{
#Html.AntiForgeryToken()
<div class="container">
<ul class="nav nav-pills">
<li class="active"><a data-toggle="pill" href="#EditGuest">Edycja - Gość</a></li>
<li><a data-toggle="pill" href="#EditContact">Edycja - Kontakt</a></li>
<li><a data-toggle="pill" href="#EditBill">Edycja - Rezerwacja</a></li>
<li><a data-toggle="pill" href="#EditPlan">Edycja - Konferencja</a></li>
</ul>
<div class="tab-content">
<div id="EditGuest" class="tab-pane fade in active">#Html.Partial("_GuestForm", new MSConference.WebUI.Models.TableViewModel())</div>
<div id="EditContact" class="tab-pane fade">#Html.Partial("_ContactForm", new MSConference.WebUI.Models.TableViewModel())</div>
<div id="EditBill" class="tab-pane fade">sgdg</div>
<div id="EditPlan" class="tab-pane fade">gsdgsgsgsg</div>
</div>
</div>
}
<div>
#Html.ActionLink("Powrót do Listy", "Index", null, new { #class = "btn btn-success" })
</div>
I tried every method of passing model I could find and understand
EDIT
Here are my Repositories. Create error comes from if (contact.ContactID == 0)
public class EFGuestRepository : IGuestRepository
{
private EfDbContext context = new EfDbContext();
public IEnumerable<Guest> Guests
{
get { return context.Guests; }
}
public void SaveGuest(Guest guest)
{
if (guest.GuestID == 0)
{
context.Guests.Add(guest);
}
else
{
Guest dbEntry = context.Guests.Find(guest.GuestID);
if (dbEntry != null)
{
dbEntry.GuestLastName = guest.GuestLastName;
dbEntry.GuestFirstName = guest.GuestFirstName;
dbEntry.GuestMiddleName = guest.GuestMiddleName;
dbEntry.GuestEmail = guest.GuestEmail;
dbEntry.GuestSex = guest.GuestSex;
}
}
context.SaveChanges();
}
public Guest DeleteGuest(int guestId)
{
Guest dbEntry = context.Guests.Find(guestId);
if (dbEntry != null)
{
context.Guests.Remove(dbEntry);
context.SaveChanges();
}
return dbEntry;
}
}
public class EFContactRepository : IContactRepository
{
private EfDbContext context = new EfDbContext();
public IEnumerable<Contact> Contacts
{
get { return context.Contacts; }
}
public void SaveContact(Contact contact)
{
if (contact.ContactID == 0)
{
contact.GuestID = contact.ContactID;
context.Contacts.Add(contact);
}
else
{
Contact dbEntry = context.Contacts.Find(contact.ContactID);
if (dbEntry != null)
{
contact.GuestID = contact.ContactID;
dbEntry.PostalCode = contact.PostalCode;
dbEntry.City = contact.City;
dbEntry.Street = contact.Street;
dbEntry.HouseNumber = contact.HouseNumber;
dbEntry.PhoneNumber = contact.PhoneNumber;
}
}
context.SaveChanges();
}
public Contact DeleteContact(int guestId)
{
Contact dbEntry = context.Contacts.Find(guestId);
if (dbEntry != null)
{
context.Contacts.Remove(dbEntry);
context.SaveChanges();
}
return dbEntry;
}
public interface IGuestRepository
{
IEnumerable<Guest> Guests { get; }
void SaveGuest(Guest guest);
Guest DeleteGuest(int guestId);
}
public interface IContactRepository
{
IEnumerable<Contact> Contacts { get; }
void SaveContact(Contact guest);
Contact DeleteContact(int guestId);
}
I've built whole project working with Adam Freeman pro asp.net mvc 5 book (SportsStore project).
Passing entities to the view isn't a good practice, and depending on what you do with them when they are returned from the view, this can expose you to data tampering. Your "TableViewModel" should just consist of the flattened fields from the guest and contact, or a GuestViewModel and ContactViewModel revealing only the keys and details you need to display/edit. Entities are designed to be associated to a DbContext. Putting a reference to them in a view model is orphaning them. When you pass them back to the controller, they become just POCO instances that are deserialized from the JSON data coming from the view. They have no change tracking etc. that you might expect from using entities while they're freshly loaded from a DbContext. You can attach them to a DbContext, but you would have to manually set the entity State to "Modified" otherwise the context does not know the entity has been changed.
Your issue as it stands right now will probably be in what your SaveGuest method is doing.
The typical MVC lifecycle for the data would be roughly:
View:
Load entity(ies) from context
Populate view models
Pass to view.
Update:
Validate view model against current session
Load entity(ies) from context based on keys
Check that view model isn't stale (last mod date / timestamp / row version matches)
Validate and copy across only details that can be updated from view model into entity
SaveChanges.
Chances are if you're not seeing changes, you're probably attaching the entity to the new context without setting the entity State to "Modified". Note that this is not recommended as you are unconditionally trusting the data coming from the client. For instance you may intend to only see that a user has modified data that you created controls for, but by attaching the entity, you leave the door open for the POST call to be intercepted or played back with any/all data on the entity being altered. You would need to load the existing entity anyways to validate that nothing that shouldn't have been changed had been changed. Another possibility is you could be reloading the entity without realizing, not copying the values across from your view model's entity before calling SaveChanges, or adding the entity to the context thinking it would update the existing row, but it is saving a completely new row with new PK.
I solved my problem by replacing
#Html.Partial("PartialView", Model)
With
#{ Html.RenderPartial("PartialView", Model);}
I also rebuilded my models
Now my entity models looks like this:
[Table("GuestsTest")]
public class Guest
{
[Key]
public int GuestID { get; set; }
public string GuestLastName { get; set; }
public string GuestFirstName { get; set; }
public string GuestMiddleName { get; set; }
public string GuestEmail { get; set; }
public string GuestSex { get; set; }
[Required]
public virtual Contact Address { get; set; }
}
[Table("ContactsTest")]
public class Contact
{
public int ContactID { get; set; }
[Key, ForeignKey("Guest")]
public int GuestID { get; set; }
public int PostalCode { get; set; }
public string City { get; set; }
public string Street { get; set; }
public string HouseNumber { get; set; }
public string PhoneNumber { get; set; }
public virtual Guest Guest { get; set; }
}
And my view models got full rebuild to this:
public class TableViewModel
{
public GuestViewModel GetGuest { get; set; }
public ContactViewModel GetContact { get; set; }
}
public class GuestViewModel
{
[Key]
[HiddenInput(DisplayValue = false)]
public int? GuestID { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "Proszę podać nazwisko.")]
[Display(Name = "Nazwisko")]
public string GuestLastName { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "Proszę podać imię.")]
[Display(Name = "Imię")]
public string GuestFirstName { get; set; }
[MaxLength(50)]
[Display(Name = "Drugie imię")]
public string GuestMiddleName { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "Proszę podać adres email.")]
[RegularExpression(".+\\#.+\\..+", ErrorMessage = "Proszę podać prawidłowy adres e-mail.")]
[Display(Name = "Email")]
public string GuestEmail { get; set; }
[MaxLength(1)]
[Required(ErrorMessage = "Proszę podać płeć.")]
public string GuestSex { get; set; }
}
public class ContactViewModel
{
[HiddenInput(DisplayValue = false)]
public int ContactID { get; set; }
[Key, ForeignKey("Guest")]
[HiddenInput(DisplayValue = false)]
public int GuestID { get; set; }
[Required(ErrorMessage = "Proszę podać kod pocztowy.")]
[Display(Name = "Kod pocztowy")]
public int PostalCode { get; set; }
[Required(ErrorMessage = "Proszę podać Miejscowość.")]
[Display(Name = "Miejscowość")]
public string City { get; set; }
[Required(ErrorMessage = "Proszę podać ulicę.")]
[Display(Name = "Ulica")]
public string Street { get; set; }
[Required(ErrorMessage = "Proszę podać numer domu/mieszkania.")]
[Display(Name = "Numer domu/mieszkania")]
public string HouseNumber { get; set; }
[Required(ErrorMessage = "Proszę podać numer telefonu.")]
[Display(Name = "Numer telefonu")]
public string PhoneNumber { get; set; }
}
Last, I overloaded my save function to work with new models

assign list items to model properties

MODEL
namespace CG.MyPollSurveyAdmin.Models
{
public class CompletePollSurvey
{
public long PollSurveyID { get; set; }
public string Name { get; set; }
public List<OptionData> Options { get; set; }
public List<QuestionData> QuestionDetails { get; set; }
}
public class QuestionData
{
public string QuestionName { get; set; }
public long QuestionID { get; set; }
public int OptionID { get; set; }
public string OptionType { get; set; }
public string Option_1 { get; set; }
public string Option_2 { get; set; }
public string Option_3 { get; set; }
public string Option_4 { get; set; }
public string Option_5 { get; set; }
}
}
CONTROLLER
private List<Question> GetQuestionsById(long PollSurveyId)
{
MemoryStream outMemoryStream = RESTFulServiceHelper.Instance.ExecuteGetMethod(Constants.Method_GetAllQuestions, Convert.ToString(Session[Constants.NTLoginID]));
DataContractJsonSerializer outDataContractJsonSerialize = new DataContractJsonSerializer(typeof(List<Question>));
List<Question> lstQuestions = outDataContractJsonSerialize.ReadObject(outMemoryStream) as List<Question>;
List<Question> question = lstQuestions.Where(p => p.PollSurveyID == PollSurveyId).ToList();
return question;
}
public ActionResult Help(long PollSurveyID=2)
{
if (Session[Constants.Session_IsAdmin] != null && Convert.ToBoolean(Session[Constants.Session_IsAdmin]))
{
CompletePollSurvey completePollSurvey = new CompletePollSurvey();
List<Question> question = GetQuestionsById(Convert.ToInt64(PollSurveyID));
return View(completePollSurvey);
}
else
{
return RedirectToAction("Login");
}
}
Here is the model and controller of my program. Till now I'm getting All the questions for poll id=2 but I'm having difficulty in retrieving element from Question List and assign it to Model List elements(or list to list assignment).
For e.g I have 5 questions for Poll=2 and in each question there are 5 options

Cannot insert the value NULL into column from unrelated entity

I'm getting a "Cannot insert null into column" error from an unrelated table when trying to add a new record for the "original" table.
I have the following two (relevant) entities:
public class Complex
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public Guid OwnerId { get; set; }
[ForeignKey("OwnerId")]
public Owner Owner { get; set; }
public Guid AddressId { get; set; }
[ForeignKey("AddressId")]
public virtual Address Address { get; set; }
public virtual ICollection<Unit> Units { get; set; }
public virtual ICollection<StaffMember> StaffMembers { get; set; }
public Complex()
{
this.Id = System.Guid.NewGuid();
this.Units = new HashSet<Unit>();
this.StaffMembers = new HashSet<StaffMember>();
}
public void AddUnit(Unit unit)
{
Units.Add(unit);
}
public void AddStaff(StaffMember staffMember)
{
StaffMembers.Add(staffMember);
}
}
and
public class Owner
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public Guid ContactInfoId { get; set; }
[ForeignKey("ContactInfoId")]
public ContactInfo ContactInfo { get; set; }
public ICollection<StaffMember> Employees { get; set; }
public ICollection<Complex> Complexes { get; set; }
public Owner()
{
this.Id = System.Guid.NewGuid();
this.Employees = new HashSet<StaffMember>();
this.Complexes = new HashSet<Complex>();
}
public void AddEmployee(StaffMember employee)
{
Employees.Add(employee);
}
public void AddComplex(Complex complex)
{
Complexes.Add(complex);
}
}
I'm trying to add a new owner in the following code:
if (ModelState.IsValid)
{
Owner newOwner = new Owner();
ContactInfo newContactInfo = new ContactInfo();
Address newAddress = new Address();
newAddress.Address1 = viewModel.ContactInfo.Address.Address1;
newAddress.Address2 = viewModel.ContactInfo.Address.Address2;
newAddress.City = viewModel.ContactInfo.Address.City;
newAddress.State = viewModel.ContactInfo.Address.State;
newAddress.Zip = viewModel.ContactInfo.Address.Zip;
newContactInfo.Address = newAddress;
newContactInfo.Email = viewModel.ContactInfo.Email;
newContactInfo.Phone1 = viewModel.ContactInfo.Phone1;
newContactInfo.Phone2 = viewModel.ContactInfo.Phone2;
newOwner.Name = viewModel.Name;
newOwner.ContactInfo = newContactInfo;
using (REMSDAL dal = new REMSDAL())
{
dal.Owners.Add(newOwner);
var result = await dal.SaveChangesAsync();
if (result > 0)
{
viewModel.ActionStatusMessageViewModel.StatusMessage = "Owner " + viewModel.Name + " added.";
viewModel.Name = "";
return View(viewModel);
}
}
}
...but getting this error:
Exception Details: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'OwnerId', table 'REMS.dbo.Complexes'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
How can I be getting an error regarding Complexes when I'm trying to add an Owner?

MVC Accessing navigation property for listboxFor

At first I should say i am compeletely newbie in MVC.
I have 3 Objects
public partial class Magazine
{
public Magazine()
{
this.NumberTitles = new HashSet<NumberTitle>();
}
public int Id { get; set; }
public int MagYear { get; set; }
public int MagNo { get; set; }
public int MagSeason { get; set; }
public string MagYear2 { get; set; }
public virtual ICollection<NumberTitle> NumberTitles { get; set; }
}
public partial class NumberTitle
{
public NumberTitle()
{
this.Articles = new HashSet<Article>();
}
public int Id { get; set; }
public int MagazineId { get; set; }
public int TitleId { get; set; }
public int position { get; set; }
public virtual ICollection<Article> Articles { get; set; }
public virtual Magazine Magazine { get; set; }
public virtual Title Title { get; set; }
}
public partial class Title
{
public Title()
{
this.ChildrenTitle = new HashSet<Title>();
this.NumberTitles = new HashSet<NumberTitle>();
}
public int Id { get; set; }
public string TitleText { get; set; }
public Nullable<int> ParentId { get; set; }
public virtual ICollection<Title> ChildrenTitle { get; set; }
public virtual Title ParentTitle { get; set; }
public virtual ICollection<NumberTitle> NumberTitles { get; set; }
}
In a View I want to have TextBox to show Magazine Number and 2 List boxes. one shows all the Available Titles and the Other just selected Titles for that Magazine Number.So I have made View Model
public class NumberTitleViewModel
{
public Magazine Magazine { get; set; }
public List<NumberTitle> NumberTitles { get; set; }
}
this is in controller. how can i get the list of titles for specified MagazineId
public ActionResult EditTitle(int id)
{
Func<IQueryable<Magazine>, IOrderedQueryable<Magazine>> orderByFunc = null;
Expression<Func<Magazine, bool>> filterExpr = null;
if (id>0)
{
filterExpr = p => p.Id.Equals(id);
}
Magazine magazine = unitOfWork.MagazineRepository.Get(filter: filterExpr, orderBy: orderByFunc, includeProperties: "").SingleOrDefault();
NumberTitleViewModel numberTitleViewMode = new NumberTitleViewModel();
numberTitleViewMode.Magazine = magazine;
Expression<Func<NumberTitle, bool>> filterExpr2 = null;
if (id > 0)
{
filterExpr2 = p => p.MagazineId.Equals(id);
}
var numberTitles = unitOfWork.NumberTitleRepository.Get(filterExpr2, null, includeProperties: "Title").ToList();
var titles = unitOfWork.TitleRepository.Get(null, null, "");
numberTitleViewMode.NumberTitles = numberTitles; ///this part doesn't show the Titles. how should access the TitleName not Id
ViewBag.titles = new SelectList(titles, "Id", "TitleText");
return View("../Panel/Magazine/EditTitle", "_BasicLayout", numberTitleViewMode);
}
Not sure what you have in your view but you should have something like:
#using NameSpace.Models
#model NameSpace.Models.NumberTitleViewModel
Then you can do something like this in your view:
foreach (NumberTitles item in #Model)
{
<label>#item.Title.TitleText</label>
}
Not exact but should get you close to what you need

EF5 ASP.NET MVC 4 Linq query not returning anything & model property null -> Code First

Im having trouble linking my loaned items to my Library for each customer. It does it fine when it goes through the "AddToLibrary" method but when it comes to retreiving it, the medialibrary is empty and the query in the IEnumerable<Item> ItemsOnLoan method is returning null. This is a very basic ASP.NET MVC 4 application and im very new to this so its probably something silly ive missed out.
I just want to be able to add an item to the loaned items table, have the list of loaned items for each customer appear in their personal Library (defined in model) and then retreive the list of their items. Below is all the code and I am using a code first approach. Thank you :)
Model
public class Customer
{
public int Id { get; set; }
public string ForeName { get; set; }
public string SurName { get; set; }
public Address address { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public string Mobile { get; set; }
public List<LoanedItem> Library { get; set; }
public Customer()
{
if (Library == null || Library.Count == 0)
{
Library = new List<LoanedItem>();
}
}
public IEnumerable<Item> ItemsOnLoan
{
get
{
var items = (from i in Library
where i.Customer.Id == this.Id
select i).OfType<item>();
return items;
}
}
}
Loaned Item model
public class LoanedItem
{
public int? Id { get; set; }
public Customer Customer { get; set; }
public MediaItem Item { get; set; }
}
ItemController --> adding to library method
public ActionResult AddToLibrary(int id)
{
Item libraryItem = db.Items.Find(id);
Customer c = db.Customers.Find(1);
LoanedItem newLoanGame = new LoanedItem()
{
Customer = c,
Item = libraryItem
};
db.LoanedItems.Add(newLoanGame);
db.SaveChanges();
return RedirectToAction("Index");
}
Customer Controller
public ActionResult ViewProfile(int id = 1)
{
Customer c = db.Customers.Find(id);
if (c == null)
{
return HttpNotFound();
}
return View(c);
}
public ActionResult GetLibraryItems(int id = 1)
{
var items = db.Customers.Find(id).ItemsOnLoan;
return View(items);
}
Context
public class LibraryContext : DbContext
{
public DbSet<Address> Addresses { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<LoanedItem> LoanedItems { get; set; }
public DbSet<Item> Items { get; set; }
public LibraryContext()
: base("LbContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CustomerConfiguration());
modelBuilder.Configurations.Add(new LoanedItemConfiguration());
modelBuilder.Entity<Item>();
modelBuilder.Entity<Address>();
base.OnModelCreating(modelBuilder);
}
}
Assuming that Proxy generation is enabled try this:
public class Customer
{
public int Id { get; set; }
public string ForeName { get; set; }
public string SurName { get; set; }
public Address address { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public string Mobile { get; set; }
public virtual ICollection<LoanedItem> ItemsOnLoan { get; set; }
public Customer()
{
}
}
using this to acccess:
public ActionResult GetLibraryItems(int id = 1)
{
var customer = db.Customers.Find(id);
if (customer != null)
{
var items = customer.ItemsOnLoan;
return View(items);
}
//handle not found or throw an exception
throw new Exception();
}
follow this link for more information on Proxies and Lazy Loading.

Resources