C# passing boolean value as message - c#

I have a ViewModel with "HasBeenShipped" which is a boolean, how in my controller would I send it to the view as;
If (hasbeenshipped = false)
my message i want to send to the view
else
Order has been shipped
And in the view how would I display one of these?
Possibly with a viewbag i thought?
Here is my controller
public ActionResult Index()
{
string currentUser = this.User.Identity.GetUserName();
List<T_shirt_Company_v3.ViewModels.MyOrdersViewModel> list = (from o in new TshirtStoreDB().Orders
.Where(o => o.Username == currentUser)
.OrderBy(o => o.OrderDate)
.Select(o => new MyOrdersViewModel()
{
OrderId = o.OrderId,
Address = o.Address,
FirstName = o.FirstName,
LastName = o.LastName,
City = o.City,
OrderDate = o.OrderDate,
PostalCode = o.PostalCode,
Total = o.Total,
HasBeenShipped = o.HasBeenShipped,
Details = (from d in o.OrderDetails
select new MyOrderDetails
{
Colour = d.Product.Colour,
Quantity = d.Quantity,
Title = d.Product.Title,
UnitPrice = d.UnitPrice
}).ToList()
}).ToList()select o).ToList();
//ViewBag.ShippedMessage = HasBeenShipped ? "blah" : "not shipped";
return View(list);

Because the ViewModel contains HasBeenShipped this should work:
View.cshtml
#model List<T_shirt_Company_v3.ViewModels.MyOrdersViewModel>
#foreach (var item in Model)
{
<span>#(item.HasBeenShipped ? "..." : "...")</span>
}
No need to use ViewBag, or perhaps only if the messages themselves have to be loaded from an outside source, which should then be done in the Controller.

In your controller use ViewBag. Such as
ViewBag.ShippedMessage = list.Where(w=>w.HasBeenShipped).Any() ? "blah" : "not shipped";
Then in your view you can access that property
<p>#ViewBag.ShippedMessage</p>

Related

LINQ Lambda for create a list with info from 3 related tables

I am trying to create a ViewModel list with info from Receipt table and then if related info exist in Reason table retreive the last Description inserted (ReceiptId related) and add it (if not just pass null) to the ViewModel Receipt list (RejectDescription). Here's the DB model:
Database Model
I tryied many ways to achieve this, at the moment this is the code that partially works for me, i say partially because in RejectDescription saves the Reason.Description if it exist else just pass null and it's ok.
The main problem is when there's many Reason.Descriptions it doesn't return and save the last one inserted (the most recent, is the one that i am looking for). Here is my code:
[HttpPost]
public ActionResult ReceiptList(string Keyword)
{
using (SEPRETEntities DBC = new SEPRETEntities())
{
long UserId = (long)Session["Id"];
IEnumerable<Receipt> receipts = DBC.Receipts.Where(x => x.PersonId == UserId && x.Active == true).ToList();
#region Search
if (!string.IsNullOrEmpty(Keyword))
{
Keyword = Keyword.ToLower();
receipts = receipts.Where(x => x.Person.Name.ToLower().Contains(Keyword) ||
x.Person.MiddleName.ToLower().Contains(Keyword) ||
x.Person.LastName.ToLower().Contains(Keyword) ||
x.Person.Email.ToLower().Contains(Keyword) ||
x.Person.Enrollment.ToLower().Contains(Keyword) ||
x.Person.Career.ToLower().Contains(Keyword) ||
x.Payment.Name.ToLower().Contains(Keyword) ||
x.Payment.Price.ToString().ToLower().Contains(Keyword) ||
x.Method.Name.ToLower().Contains(Keyword) ||
x.Phase.Name.ToLower().Contains(Keyword) ||
x.TimeCreated.ToString().ToLower().Contains(Keyword) ||
x.Voucher.ToString().ToLower().Contains(Keyword)
);
}
#endregion
List<ReceiptVM> ReceiptList = receipts.Select(x => new ReceiptVM
{
Id = x.Id,
PaymentId = x.PaymentId,
Enrollment = x.Person.Enrollment,
Career = x.Person.Career,
PersonName = string.Concat(x.Person.Name, " ", x.Person.MiddleName, " ", x.Person.LastName),
Email = x.Person.Email,
PaymentName = x.Payment.Name,
MethodName = x.Method.Name,
Voucher = x.Voucher,
Image = x.Image,
PhaseId = x.Phase.Id,
PriceFormatted = x.Payment.Price.ToString("C"),
Active = x.Active,
TimeCreatedFormatted = x.TimeCreated.ToString(),
RejectDescription = x.Rejections.FirstOrDefault(y => y.ReasonId == y.Reason.Id)?.Reason.Description
}).ToList();
return PartialView("~/Views/Receipt/_SearchReceipt.cshtml", ReceiptList);
}
}
For you information i am kinda newbie working on C# and ASP.NET MVC.Not sure if there's a better way to achieve this or something, any advice or tip is pretty appreciated.
Thank you and sorry for my bad english
You have to order reject reasons by Id which will fetch recent reason like below :
RejectDescription = x.Rejections.OrderByDescending(x=>x.Reason.Id).FirstOrDefault(y => y.ReasonId == y.Reason.Id)?.Reason.Description
Or you can use LastOrDefault to get most recent one like below:
RejectDescription = x.Rejections.LastOrDefault(y => y.ReasonId == y.Reason.Id)?.Reason.Description
List<ReceiptVM> ReceiptList = receipts.Select(x => new ReceiptVM
{
Id = x.Id,
PaymentId = x.PaymentId,
Enrollment = x.Person.Enrollment,
Career = x.Person.Career,
PersonName = string.Concat(x.Person.Name, " ", x.Person.MiddleName, " ", x.Person.LastName),
Email = x.Person.Email,
PaymentName = x.Payment.Name,
MethodName = x.Method.Name,
Voucher = x.Voucher,
Image = x.Image,
PhaseId = x.Phase.Id,
PriceFormatted = x.Payment.Price.ToString("C"),
Active = x.Active,
TimeCreatedFormatted = x.TimeCreated.ToString(),
RejectDescription = x.Rejections.OrderByDescending(x=>x.Reason.Id).FirstOrDefault(y => y.ReasonId == y.Reason.Id)?.Reason.Description
}).ToList();

How to get data only relating to the session of the staff members StaffID

I have figured out that to get the staff members from a company I use the following:
public ActionResult Index()
{
int staffID = (int)Session["StaffID"];
var staffRecord = db.Staffs.FirstOrDefault(staff => staff.StaffID == staffID);
var company = staffRecord.Company;
var staffForCompany = company.Staffs;
return View(staffForCompany);
}
and this gets the bookings for that staff/company:
public ActionResult Index()
{
int staffID = (int)Session["StaffID"];
var staffRecord = db.Staffs.FirstOrDefault(staff => staff.StaffID == staffID);
var company = staffRecord.Company;
var bookingsForCompany = company.Bookings;
return View(bookingsForCompany);
}
What I am wanting to know is how do I get data from a table that is not directly associated with the staff/company tables.
I am wanting the Customers that relate to the company of the staff member logged in.
See image here http://www.adamoxenhamsmith.co.uk/Uploads/download.jpg
From the ER diagram given in the image, it seems Company has 1..n bookings and each booking is tied to 1 Customer
This should work:
var customers = staffRecord.Company.Bookings.Select(b => b.Customer);
This should work:
var customers = db.Staffs
.Where(s => s.StaffID == staffId)
.Select(s => s.Company)
.SelectMany(c => c.Bookings)
.Select(bk => bk.Customer)
.ToList();

Sorting multiple LINQ results of different models as one list in MVC

I am trying to sort a list of users that are either students, colleagues or guests and sort them in my view based on their names.
Here is the code:
public ActionResult Index()
{
var db = new PraktikumDataContext();
var model = new List<AdminUserListItem>();
var studs = (from stud in db.Students select new AdminUserListItem() {Name = stud.FH_Angehörige.Name, LastLogin = stud.FH_Angehörige.FE_Nutzer.Letzter_Login, Rolle = "Student"}).OrderBy(stud => stud.Name);
model.AddRange(studs);
var mits = (from mit in db.Mitarbeiters select new AdminUserListItem() {Name = mit.FH_Angehörige.Name, LastLogin = mit.FH_Angehörige.FE_Nutzer.Letzter_Login, Rolle = "Mitarbeiter"}).OrderBy(stud => stud.Name);
model.AddRange(mits);
var gasts = (from gast in db.Gasts select new AdminUserListItem() {Name = gast.Name, LastLogin = gast.FE_Nutzer.Letzter_Login, Rolle = "Gast"}).OrderBy(stud => stud.Name);
model.AddRange(gasts);
model = model.OrderByDescending()
return View(model);
}
What I've already done with OrderBy sorts each model in it's own scope, however since I have 3 models, I am a little bit confused now how to somehow make them to be seen as one list and then sort them and show them in my website.
Consider using a LINQ union that makes a single call to the server:
public ActionResult Index()
{
var db = new PraktikumDataContext();
var model =
(from stud in db.Students
select new AdminUserListItem()
{
Name = stud.FH_Angehörige.Name,
LastLogin = stud.FH_Angehörige.FE_Nutzer.Letzter_Login,
Rolle = "Student"}
).Union(
from mit in db.Mitarbeiters
select new AdminUserListItem()
{
Name = mit.FH_Angehörige.Name,
LastLogin = mit.FH_Angehörige.FE_Nutzer.Letzter_Login,
Rolle = "Mitarbeiter"}
).Union(
from gast in db.Gasts
select new AdminUserListItem()
{
Name = gast.FH_Angehörige.Name,
LastLogin = gast.FE_Nutzer.Letzter_Login,
Rolle = "Gast"}
)
.OrderByDescending(a => a.Name)
.ToList();
return View(model);
}

Populate a view model with a data model with a method aswell

i need to populate my articles ViewModel with a model that has the database data in it, but i have a method that i need to assign to one of my properties
The list of images is the property that needs the method on it.
The method is called once for every item in the list of articles.
Here is my code:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var query = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName,
}).ToList();
articleViewModel.Images = imageService.GetImagesForArticle(articlemodel.Id.ToString());
return View(query);
}
I have also tried putting the method inside the linq:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var query = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName,
Images = imageService.GetImagesForArticle(a.Id.ToString())
}).ToList();
return View(query);
}
it throws an exception of:
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[New_MinecraftNews_Webiste_MVC.Models.ImageInfo] GetImagesForArticle
I added a foreach loop at the end insted of anything else and it works:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var modelList = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName
}).ToList();
foreach (var model in modelList)
{
model.Images = imageService.GetImagesForArticle(model.Id.ToString());
}
return View(modelList);
}

Get data from multiple tables at once

I used ADO.NET Entity Database Model (auto-generated) for my angularJS application using database model shown below:
Currently I am using this code to get all data from Contact table:
ContactsEntities db = new ContactsEntities();
public JsonResult GetAll()
{
return Json(db.Contacts.ToList(), JsonRequestBehavior.AllowGet);
}
What I want to achieve is to get all data from database. Is there way to get all data in single "query" or do I need to call
return Json(db.{MODEL NAME}.ToList(), JsonRequestBehavior.AllowGet);
for each model(table) to get data? Is there better solution to get all data from database or do I need to call each model separately?
You should try something like this:
var data = (from c in db.Contacts
from e in db.Emails.Where(x => x.id == c.id_email).DefaultIfEmpty()
from p in db.Phones.Where(x => x.id == c.id_phone).DefaultIfEmpty()
from t in db.Tags.Where(x => x.id == c.id_tag).DefaultIfEmpty()
select new
{
id = c.id,
phone = p.number,
email = e.email1,
tag = t.tag1,
firstname = c.firstname,
lastname = c.lastname,
address = c.address,
city = c.city,
bookmarked = c.bookmarked,
notes = c.notes
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
Or if you want to prepare yourself for the future, when you add multiple properties to the Contact/Email/... classes and don't want to change your code:
var data = (from c in db.Contacts
from e in db.Emails.Where(x => x.id == c.id_email).DefaultIfEmpty()
from p in db.Phones.Where(x => x.id == c.id_phone).DefaultIfEmpty()
from t in db.Tags.Where(x => x.id == c.id_tag).DefaultIfEmpty()
select new
{
Contact = c,
Email = e,
Phone = p,
Tag = t
}).ToList();

Categories

Resources