I am trying, to no avail to display a dropdown list of all units a user doesnt already have. So i have List A with all Units and List B with all Units the user has. What i want is List C which is basically List A with List B removed from it. I have so far managed to filter out the data but i cant seem to display it in my View. All i get is a blank dropdown list. Can anyone see where im going wrong??
public ActionResult AddUnit(String usrCode)
{
var units = unitsClient.GetAllunits();
var allunitsCode = (from s in units select s.unitCode).ToList();
var thisUnitCode = (from s in db.Units
where s.UsrCode == usrCode
select s.UnitCode).ToList();
var notGot = allunitsCode.Except(thisUnitCode);
List<unitsummaryDTO> list = UnitList(units, notGot);
ViewBag.unitCode = new SelectList(list, "unitCode", "unitTitle");
var model = new UserUnit { UsrCode = usrCode };
return View("AddUnit", model);
}
private List<unitsummaryDTO> UnitList(unitsService.unitsDTO[] units, IEnumerable<string> notGot)
{
var allunits = unitsClient.GetAllunits();
var allunitsCode = (from s in allunits select s.unitCode).ToList();
IEnumerable<String> list1 = allunitsCode;
IEnumerable<String> list2 = notGot;
var listFinal = list1.Union(list2).toList;
return listFinal.Select(x => new unitsummaryDTO(){unitCode = x}).ToList();
}
This is my View model. But all i get is a blank drop down?? Can anyone help me out.
#model Projv1.UserUnit
#Html.HiddenFor(model => model.unitCode)
#Html.DropDownList("UnitCode")
It would be blank because #Html.DropDownList("UnitCode") doesn't have a source. If you look at MSDN for Html.DropDownList, the one your most likely trying to use is DropDownList(String, IEnumerable<SelectListItem>).
Your putting your select list into the ViewBag as unitCode so try:
#Html.DropDownList("Unit Code", ViewBag.unitCode);
A much easier way of handling this is to extend UserUnit as a ViewModel (or create something) to have the items needed by the SelectList on it and let MVC do the heavy lifting in the binding.
public class UserUnit
{
// ... other properties
IEnumerable<unitsummaryDTO> UnitCodes { get; set; }
public string MyUnitCode { get; set; }
}
Then
#Html.DropDownListFor(n => n.MyUnitCode,
new SelectList(Model.UnitCodes, "unitCode", "unitTitle"))
Related
I have struggle with adding the grouped data table with linq query to model property.
Here's my model
public class Ports
{
public String city { get; set; }
}
and here's my controller
public ActionResult ShipSchedule()
{
DatabaseContext db = new DatabaseContext();
var Ports = new Ports();
Ports.city = from m in db.ports_data group m by new { m.city } into n select new { n.Key.city };
return View();
}
I've replaced the model part to List<> and replaced again to another, but this part
Ports.city = (from m in db.ports_data group m by new { m.city } into n select new { newcity = n.Key.city }).ToList();
is still tell me that part cannot convert type 'system.collections.generic.list<<anonymous type: string newcity>>' to 'system.collections.generic.list<string>'
Did anyone know the correct ways from this?
and one more thing, I want to display that part to my view in dropdown, if anyone have a better ways
here's my view
#model example.Models.Ports
#{
List<SelectListItem> listItems = new List<SelectListItem>();
foreach (var mod in Model.city)
{
listItems.Add(new SelectListItem
{
Text = mod.ToString(),
Value = mod.ToString()
});
}
}
#Html.DropDownListFor(model => model.selected, listItems, "-- Select item --")
the error is telling you exactly what is wrong, you have a string but are trying to assign a list to it (two very different objects), you can simply:
public class Ports
{
public List<String> cities { get; set; }
}
which will make that string be valid, but a better practice would be make "Ports" a list and use it as List<Port> and each port will contain "city" (and all the other port properties).
but in any case to get all ports from the database you probably can do:
var ports = db.ports_data.ToList();
that should give you a list with all the ports in your database (no need to create that New Ports() and populate it, if you need to group by city it should be as easy as:
var ports = db.ports_data.GroupBy(x=>x.city).ToList();
in the comment you mentioned that you are getting duplicates, for that you may need distinct, but if you don't need duplicates you shouldn't be adding duplicates to the database to start with, so we would be touching the wrong end here, but in any case I believe you need Distinct() if combined with a select you will get only cities, different ones if there is duplicates:
var portsCities = db.ports_data.Select(x=>x.city).Distinct().ToList();
that will result in a List<string> of cities, all different
as you can see Linq have many ways to get exactly the data you need, I would play around with it and experiment, best way to learn!
I would also try to use LINQ method (as the examples above) if you are starting, it is easier to manage (more object oriented) you can see some examples here
I'm pretty new to MVC so there might be a super simple answer to this.
The following is my current controller code:
public class StudentBanController : Controller
{
SWGS_GlobalDataEntities DataContext = new SWGS_GlobalDataEntities();
// GET: StudentBan
public ActionResult DisplayBans()
{
var theData = DataContext.tblGlobalLogOnLogOffStudentBans.ToList();
List<StudentBanDisplayViewModel> BanList = theData
.Select(viewModel => new StudentBanDisplayViewModel
{
ID = viewModel.ID,
UserID = viewModel.UserID,
StartBan = viewModel.StartBan,
EndBan = viewModel.EndBan
}).Where(b => b.EndBan > DateTime.Today).ToList();
return PartialView(BanList);
}
}
What I am trying to do is create a list, but I only want it to contain records for Distinct UserID's and I cant figure how to do it.
I have tried .distinct in various places and also grouping by user ID and selecting .first but nothing seems to do the job.
Any advice?
Try the following
List<StudentBanDisplayViewModel> BanList = theData
.Select(viewModel => new StudentBanDisplayViewModel
{
ID = viewModel.ID,
UserID = viewModel.UserID,
StartBan = viewModel.StartBan,
EndBan = viewModel.EndBan
}).Where(b => b.EndBan > DateTime.Today)
.DistinctBy(s => new {s.UserID}).ToList();
How to remove duplicates from collection using IEqualityComparer, LinQ Distinct
You will require the following
https://code.google.com/p/morelinq/source/browse/MoreLinq/DistinctBy.cs?r=d4396b9ff63932be0ab07c36452a481d20f96307
I am trying to add one list into another but it is giving me error of The best overloaded method match for 'System.Collection.Generic.List.AddRange(System.Collections.Generic.IEnumerable)' has some invalid arguments
My code is:
public ActionResult RegisteredEvent(string Cno)
{
if (Request.IsAjaxRequest())
{
List<tblEvent> eventlist = new List<tblEvent>();
List<RegisteredEvent> list = new List<RegisteredEvent>();
var db = new clubDataContext();
int[] eventIds = (from m in db.EventRegistrations where m.Cno == Cno select m.Event_Id).ToArray();
int i = 1;
foreach (var item in eventIds)
{
list = (from m in db.tblEvents
where item.Equals(m.EventId)
select new RegisteredEvent()
{
id = m.EventId,
caption = m.Caption,
description = m.Description,
date = m.Date.ToString()
}).ToList();
eventlist.AddRange(list); //Here I am getting error
}
ViewBag.eventDetail = eventlist;
return PartialView("RegisteredEvent");
Simply speaking, you can only concatenate lists of the same type.¹
eventlist is a List<tblEvent>
list is a List<RegisteredEvent>
¹ This is not entirely correct: Since IEnumerable is covariant, it is actually possible to add entries of a List<S> to a List<T>, if S is a subtype of T.
The T in List<T> needs to have the same type or inherent from the same base type
List<RegisteredEvent> eventlist
List<RegisteredEvent> list
or
List<tblEvent> eventlist
List<tblEvent> list
You can use IEnumerable.Select as this (I don't know the structure of tblEvent, so adapt this at your code.
eventlist.AddRange(list.Select(x => new tblEvent{ id = x.id, caption = x.caption, ... }));
But the best way is to create directly a tblEvent
//the list sent to View
eventlist = (from m in db.tblEvents
where item.Equals(m.EventId)
select new tblEvent() //here
{
id = m.EventId,
caption = m.Caption,
description = m.Description,
date = m.Date.ToString()
}).ToList();
I am using MVC4 and what I want to do is use a dropdown connected to my search box to search for the selected property. How would I am stuck on the Text= prop.Name. How could I go through and access all of the properties using this.
My Controller
public ActionResult SearchIndex(string searchString)
{
var selectListItems = new List<SelectListItem>();
var first = db.BloodStored.First();
foreach(var item in first.GetType().GetProperties())
{
selectListItems.Add(new SelectListItem(){ Text = item.Name, Value = selectListItems.Count.ToString()});
}
IEnumerable<SelectListItem> enumSelectList = selectListItems;
ViewBag.SearchFields = enumSelectList;
var bloodSearch = from m in db.BloodStored
select m;
if (!String.IsNullOrEmpty(searchString))
{
bloodSearch = bloodSearch.Where(s => string.Compare(GetValue(s, propertyName), searchString) == 0);
}
return View(bloodSearch);
}
The selectlist is working now I just need to go over my searchstring and how to pass two parameters now.
I'm not quite sure what you're asking. If you want to create a list of objects with the property Text set to the property name of the object, you could get the first object in the BloodStored enumerable and create a list of anonymous types:
// Get one instance and then iterate all the properties
var selectListItems = new List<object>();
var first = db.BloodStore.First();
foreach(var item in first.GetType().GetProperties()){
selectListItems.Add(new (){ Text = item.Name});
}
ViewBag.SearchFields = selectListItems;
In the following code that returns a list:
public List<Customer> GeAllCust()
{
var results = db.Customers
.Select(x => new { x.CustName, x.CustEmail, x.CustAddress, x.CustContactNo })
.ToList()
return results;
}
I get an error reporting that C# can't convert the list:
Error: Cannot implicitly convert type System.Collections.Generic.List<AnonymousType#1> to System.Collections.Generic.List<WebApplication2.Customer>
Why is that?
Here's a screenshot showing some additional information that Visual Studio provides in a tooltip for the error:
Is it right way to return some columns instead of whole table....?
public object GeAllCust()
{
var results = db.Customers.Select(x => new { x.CustName, x.CustEmail, x.CustAddress, x.CustContactNo }).ToList();
return results;
}
When you look the code:
x => new { ... }
This creates a new anonymous type. If you don't need to pull back only a particular set of columns, you can just do the following:
return db.Customers.ToList();
This assumes that Customers is an IEnumerable<Customer>, which should match up with what you are trying to return.
Edit
You have noted that you only want to return a certain subset of columns. If you want any sort of compiler help when coding this, you need to make a custom class to hold the values:
public class CustomerMinInfo
{
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public int? ContactNumber { get; set; }
}
Then change your function to the following:
public List<CustomerMinInfo> GetAllCust()
{
var results = db.Customers.Select(x => new CustomerMinInfo()
{
Name = x.CustName,
Email = x.Email,
Address = x.Address,
ContactNumber = x.CustContactNo
})
.ToList();
return results;
}
This will work, however, you will lose all relationship to the database context. This means if you update the returned values, it will not stick it back into the database.
Also, just to repeat my comment, returning more columns (with the exception of byte arrays) does not necessarily mean longer execution time. Returning a lot of rows means more execution time. Your function is returning every single customer in the database, which when your system grows, will start to hang your program, even with the reduced amount of columns.
You are selecting to an anonymous type, which is not a Customer.
If you want to do (sort of) this, you can write it like this:
return db.Customers.Select(x => new Customer { Name = x.CustName, Email = x.CustEmail, Address = x.CustAddress, ContactNo = x.ContactNo }).ToList();
This assumes the properties on your Customer object are what I called them.
** EDIT ** Per your comment,
If you want to return a subset of the table, you can do one of two things:
Return the translated form of Customer as I specified above, or:
Create a new class for your business layer that only has only those four fields, and change your method to return a List<ShrunkenCustomer> (assuming ShunkenCustomer is the name that you choose for your new class.)
GetAllCust() is supposed to return a List of Customer, Select New will create a list of Anonymous Types, you need to return a list of Customer from your query.
try:
var results = db.Customers.Select( new Customer{CustName = x.CustName}).ToList(); //include other fields
I guess Customer is a class you have defined yourself?
The my suggestion would be to do something like the following:
var results = db.Customers.Select(x => new Customer(x.Custname, x.CustEmail, x.CustAddress, x.CustContactNo)).ToList();
The reason is that you are trying to return a list of Customer but the results from your link is an anonymous class containing those four values.
This would of course require that you have a constructor that takes those four values.
Basically whatever u got in var type, loop on that and store it in list<> object then loop and achieve ur target.Here I m posting code for Master details.
List obj = new List();
var orderlist = (from a in db.Order_Master
join b in db.UserAccounts on a.User_Id equals b.Id into abc
from b in abc.DefaultIfEmpty()
select new
{
Order_Id = a.Order_Id,
User_Name = b.FirstName,
Order_Date = a.Order_Date,
Tot_Qty = a.Tot_Qty,
Tot_Price = a.Tot_Price,
Order_Status = a.Order_Status,
Payment_Mode = a.Payment_Mode,
Address_Id = a.Address_Id
});
List<MasterOrder> ob = new List<MasterOrder>();
foreach (var item in orderlist)
{
MasterOrder clr = new MasterOrder();
clr.Order_Id = item.Order_Id;
clr.User_Name = item.User_Name;
clr.Order_Date = item.Order_Date;
clr.Tot_Qty = item.Tot_Qty;
clr.Tot_Price = item.Tot_Price;
clr.Order_Status = item.Order_Status;
clr.Payment_Mode = item.Payment_Mode;
clr.Address_Id = item.Address_Id;
ob.Add(clr);
}
using(ecom_storeEntities en=new ecom_storeEntities())
{
var Masterlist = en.Order_Master.OrderByDescending(a => a.Order_Id).ToList();
foreach (var i in ob)
{
var Child = en.Order_Child.Where(a => a.Order_Id==i.Order_Id).ToList();
obj.Add(new OrderMasterChild
{
Master = i,
Childs = Child
});
}
}