How to retrieve list of data in model - asp.net-mvc

I have data in model and I used to store that data in session as below in controller
if (providerListingModel.ServiceDetails != null && providerListingModel.ServiceDetails.Count > 0)
Session["ServiceDetails"] = providerListingModel.ServiceDetails;
else
Session["ServiceDetails"] = null;
and for retrieving I had used the logic as
if (Session["ServiceDetails"] != null)
{
if (providerListingModel.ServiceDetails == null)
{
List<ServiceDetail> sam = (List<ServiceDetail>)Session["ServiceDetails"];
foreach (var items in sam)
{
var sd = new ServiceDetail();
sd.Id = items.Id;
sd.CategoryServiceId = items.CategoryServiceId;
sd.ServiceType = items.ServiceType;
sd.ServicePrice = items.ServicePrice;
sd.IsSelected = items.IsSelected;
sd.ProviderListingId = providerListingModel.ProviderListingId;
providerListingModel.ServiceDetails.Add(sd);
}
}
Session["ServiceDetails"] = null;
}
The session contains data but on providerListingModel.ServiceDetails.Add(sd); it throw null exception.
ServiceDetails is a class and it contains list of items
namespace xyz.DAL
{
using System;
using System.Collections.Generic;
public partial class ServiceDetail
{
public int Id { get; set; }
public int ProviderListingId { get; set; }
public Nullable<int> CategoryServiceId { get; set; }
public string ServiceType { get; set; }
public Nullable<int> ServicePrice { get; set; }
public string CustomeService { get; set; }
public Nullable<bool> IsSelected { get; set; }
public virtual CategoryService CategoryService { get; set; }
public virtual ProviderListing ProviderListing { get; set; }
}
}
am I missing some code?
As I am new I don't know what I am doing wrong

You are inserting the item to null value, so it throws an error. Create new instance of the list and add an item to collection.
if(providerListingModel.ServiceDetails ==null)
providerListingModel.ServiceDetails = new List<ServiceDetail>();

Related

Cannot Add Previously Inserted Object to Another Object (Entity Framework)

I have the EF classes OAFile and Email. I am loading the emails from the server and storing in the repository. The user can then list the e-mails and "associate" them with the selected file.
The email object is previously inserted into the repository, and I want to get the count of the emails of the file.
file.Emails.Add(email)
adds the email to the file object, but it is not being saved.
file.Emails.Count
returns always 0.
The email.FileID field is saved correctly.
What am I missing? How can get the number of email by calling file.Emails.Count?
[HttpPost]
[ValidateInput(false)]
public ActionResult AssignEmail(int emailId, int assignedTo)
{
if (emailId > 0 && assignedTo > 0)
{
Email email = repository.Emails.FirstOrDefault(x => x.EmailID == emailId);
OAFile file = repository.OAFiles.FirstOrDefault(x => x.FileID == assignedTo);
if (email != null && file != null)
{
email.FileID = assignedTo;
email.AssignedByID = HttpContext.User.Identity.GetUserId();
file.Emails.Add(email);
repository.Save();
return Json(new { success = true }, JsonRequestBehavior.DenyGet);
}
else
{
return Json(new { success = false }, JsonRequestBehavior.DenyGet);
}
}
else
{
return Json(new { success = false }, JsonRequestBehavior.DenyGet);
}
}
The Email class:
public class Email
{
public Email()
{
Attachments = new HashSet<EmailAttachment>();
}
[Key]
public int EmailID { get; set; }
public string EmailIdentifier { get; set; }
public int MessageNumber { get; set; }
public string From { get; set; }
public string Subject { get; set; }
public DateTime DateSent { get; set; }
public string Body { get; set; }
public int? FileID { get; set; }
public string AssignedByID { get; set; }
public string AssignedToID { get; set; }
public string EmailType { get; set; }
public ICollection<EmailAttachment> Attachments { get; set; }
[ForeignKey("FileID")]
public virtual OAFile OAFile { get; set; }
[ForeignKey("AssignedByID")]
public virtual AppUser AssignedBy { get; set; }
[ForeignKey("AssignedToID")]
public virtual AppUser AssignedTo { get; set; }
}
and the OAFile class:
public class OAFile
{
public OAFile()
{
Services = new HashSet<Service>();
Documents = new HashSet<Document>();
Notes = new HashSet<Note>();
Forms = new HashSet<Form>();
Emails = new HashSet<Email>();
}
[Key]
public int FileID { get; set; }
[Required]
public int CompanyID { get; set; }
[Required]
[StringLength(14)]
public string OurFileName { get; set; }
[Required]
[StringLength(100)]
public string CompanyFileName { get; set; }
[Required]
public string AppUserId_Creator { get; set; }
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
public DateTime CreatedOn { get; set; }
public int ClientID { get; set; }
[ForeignKey("ClientID")]
public virtual Client Client { get; set; }
public virtual ICollection<Service> Services { get; set; }
public ICollection<Document> Documents { get; set; }
public ICollection<Note> Notes { get; set; }
public ICollection<Form> Forms { get; set; }
public ICollection<Email> Emails { get; set; }
public virtual Company Companies { get; set; }
[ForeignKey("AppUserId_Creator")]
public virtual AppUser AppUsers_Creator { get; set; }
}
EDIT: I am calling the file.Emails.Count statement below to check whether the file has any emails associated with it.
public bool IsFileEmpty(int fileId)
{
bool isFileEmpty = true;
OAFile file = repository.FindOAFile(fileId);
if (file.Services.Count > 0 || file.Documents.Count > 0
|| file.Forms.Count > 0 || file.Notes.Count > 0 || file.CCTable != null || file.AccountingTable != null
|| file.Emails.Count > 0
)
{
isFileEmpty = false;
}
return isFileEmpty;
}
EDIT 2: I am calling the IsFileEmpty() method in another controller (HomeController.cs) while populating view model for search results. The results rows display the Delete link if the file is empty.
public ActionResult FilesSearch(FileSearchViewModel viewModel)
{
var files = !string.IsNullOrWhiteSpace(viewModel.Keyword) ? repository.FindOAFiles(viewModel.Keyword) : repository.OAFiles;
var sortedFile = files.Where(x => x.IsFileOpen).OrderByDescending(x => x.CreatedOn).ToList();
sortedFile.AddRange(files.Where(x => !x.IsFileOpen).OrderByDescending(x => x.CreatedOn));
var resultsList = new List<FileSearchResultsViewModel>();
foreach (OAFile file in sortedFile)
{
var resultsViewModel = new FileSearchResultsViewModel();
resultsViewModel.oAFile = file;
resultsViewModel.isFileEmpty = IsFileEmpty(file.FileID);
resultsList.Add(resultsViewModel);
}
return PartialView("_FilesSearch", resultsList);
}

Adding new entries over entity navigation property collection

I need to create a generic way to add missing languages entries to all entities in which implements an specific interface. I found out how to get my collection property, but I still don't know how to add new values on it before proceed to save.
Following a piece of my public override int SaveChanges() handling.
foreach (var translationEntity in ChangeTracker.Entries(<ITranslation>))
{
if (translationEntity.State == EntityState.Added)
{
var translationEntries = translationEntity.Entity.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.CanWrite &&
x.GetGetMethod().IsVirtual &&
x.PropertyType.IsGenericType == true &&
typeof(IEnumerable<ILanguage>).IsAssignableFrom(x.PropertyType) == true);
foreach (var translationEntry in translationEntries)
{
//Add missing items.
}
}
}
Classes code samples
public partial class FileType : ITranslation
{
public long FileTypeId { get; set; }
public string AcceptType { get; set; }
public virtual ICollection<FileTypeTranslation> FileTypeTranslations { get; set; }
public FileType()
{
this.FileTypeTranslations = new HashSet<FileTypeTranslation>();
}
}
public class FileTypeTranslation : EntityTranslation<long, FileType>, ILanguage
{
[Required]
public string TypeName { get; set; }
}
public partial class ElementType : ITranslation
{
public long ElementTypeId { get; set; }
public string Code { get; set; }
public virtual ICollection<ElementTypeTranslation> ElementTypeTranslations { get; set; }
public ElementType()
{
this.ElementTypeTranslations = new HashSet<FileTypeTranslation>();
}
}
public class ElementTypeTranslation : EntityTranslation<long, ElementType>, ILanguage
{
[Required]
public string Description { get; set; }
}
Entries from ChangeTracker have property called Entity which holds original entity
foreach (var fileType in ChangeTracker.Entries(<FileType>))
{
fileType.Entity.FileTypeTranslations.Add();
}
and for ElementType:
foreach (var elementType in ChangeTracker.Entries(<ElementType>))
{
elementType.Entity.ElementTypeTranslations.Add();
}
I didn't test, but it was too long to paste in comment.

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?

How create view for show cookie's info in asp.net mvc using razor?

I'm developing an online store using asp.net mvc 5 and I used cookie for add goods to cart . I want to have a page to show selected items (in cookie) and I don't know how do it, I just wrote an action result for it named Basket . I should use #model List<BasketVM> in my view but when don't know how ?!
could anyone help me please ?
Thanks
GoodController
[HttpGet]
public ActionResult Basket()
{
GoodDetailsRepositories blGoodDetails = new GoodDetailsRepositories();
List<BasketVM> listBasket = new List<BasketVM>();
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = Request.Cookies.Count - 1; i >= 0; i--)
{
if (lst.Where(p => p.Name == Request.Cookies[i].Name).Any() == false)
lst.Add(Request.Cookies[i]);
}
foreach (var item in lst.Where(p => p.Name.StartsWith("NishtmanCart_")))
{
listBasket.Add(new BasketVM {
GoodDetails = blGoodDetails.Find(Convert.ToInt32(item.Name.Substring(13))), Count =Convert.ToInt32(item.Value) });
}
return View(listBasket);
}
BasketVM.cs
public class BasketVM
{
public NP1.Models.GoodDetail GoodDetails { get; set; }
public int Count { get; set; }
}
GoodDetails.cs
public partial class GoodDetail
{
public GoodDetail()
{
this.FactorItems = new HashSet<FactorItem>();
}
public int DetailsGoodID { get; set; }
public int FKSubGoods { get; set; }
public string NishtmanCode { get; set; }
public string DetailsColor { get; set; }
public string DetailsExist { get; set; }
public long DetailsNowPrice { get; set; }
public Nullable<long> DetailsPrePrice { get; set; }
public string DetailsName { get; set; }
public string DetailsLeatherType { get; set; }
public string DetailsWeight { get; set; }
public string DetailsSize { get; set; }
public string DetailsProducer { get; set; }
public string DetailsExtraInfo { get; set; }
public string DetailsURL { get; set; }
public string DetailsKeyWords { get; set; }
public string DetailsTags { get; set; }
public int DetailsLike { get; set; }
public int DetailsDisLike { get; set; }
public string DetailsImage1 { get; set; }
public string DetailsSmallImage1 { get; set; }
public string DetailsImage2 { get; set; }
public string DetailsSmallImage2 { get; set; }
public string DetailsImage3 { get; set; }
public string DetailsSmallImage3 { get; set; }
public string DetailsImage4 { get; set; }
public string DetailsSmallImage4 { get; set; }
public virtual SubGood SubGood { get; set; }
public virtual ICollection<FactorItem> FactorItems { get; set; }
}
Add to cart code
public ActionResult AddToCart (int Id , int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//Edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//Add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = 0; i < Request.Cookies.Count; i++ )
{
lst.Add(Request.Cookies[i]);
}
bool isGet = Request.HttpMethod == "GET";
int CartCount = lst.Where(p => p.Name.StartsWith("NishtmanCart_") && p.HttpOnly != isGet).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("Good added successfully", MessageType.Success).Script,
Html = "cart items (" + CartCount.ToString() + ")"
}
);
}
catch(Exception)
{
return Json(new MyJsonData()
{
Success = false,
Script = "alert('Good didn't add');",
Html = ""
}
);
}
}
with what name you are saving the cookies you can retrieve like this let say userid u want to get rest what you have wriiten will work:
if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Userid"))
{
HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Userid"];
// retrieve cookie data here
}
how to call in view :
Viewbag.userid = #Request.Cookies["Userid"].value
In order to read a cookie client-side it needs to be created with the HttpOnly flag set to false.
Please go thorugh the below already asked question.
MVC Access stored cookie

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