My problem is pretty simple. Lets say I have a dropdown with users.
in the database i have 3 fields for my user table:
user_id
user_name
user_firstname
in my MVC app i want to link those users to projects. so thats why i want the dropdown.
now, i want to have a selectlist, with the ID as the value, and the firstname AND lastname to be the 'text'
SelectList sl = new SelectList(users, "user_id", "user_name");
now how do i get the first name also in the text? this should be fairly easy, but seems it isnt...
Use LINQ to transform your list of users into a list of SelectListItem.
var selectOptions =
from u in yourUserQuery
select new SelectListItem {
Value = u.user_id,
Text = u.user_firstname + " " + u. user_name
};
You can then convert that to a SelectList however you see fit. I personally like to define a .ToSelectList() extension method for IEnumerable<SelectListItem>, but to each his own.
You need to build a list from your database in the format you need. Here is what I did after my database read into a DataTable,
IList<UsrInfo> MyResultList = new List<UsrInfo>();
foreach (DataRow mydataRow in myDataTable.Rows)
{
MyResultList.Add(new UsrInfo()
{
Usr_CD = mydataRow["USR_NR"].ToString().Trim(),
Usr_NA = mydataRow["USR_NA_LAST"].ToString().Trim() + " , " +
mydataRow["USR_NA_FIRST"].ToString().Trim()
});
}
return new SelectList(MyResultList, "Usr_CD", "Usr_NA");
Related
I'm experiencing a problem passing a list from a controller to a view. Doing it this way works fine but I don't want to be passing the entire table.
What I want to do is pass just the results of the studies query:
ViewBag.studyList = new SelectList(_context.Studies.OrderBy(p => p.Name), "Id", "Name");
but if I put studies instead of _context.Studies like this:
var studies = (from t in _context.Studies
where !((from s in _context.Studies
join sn in _context.StudyNodes on s.Id equals sn.StudyId
where sn.NodeId == id
select s.Id).ToList()).Contains(t.Id)
select new BundleNodeViewModel
{
StudyId = t.Id,
StudyName = t.Name
}).ToList();
ViewBag.studyList = new SelectList(studies.OrderBy(p => p.StudyName), "Id", "Name");
The code throws a null exception error in the view.
How can this be a problem? I need to pass the filtered results as per the studies query and not the entire list which is the only way it seems to work.
Can someone help please so I can pass studies and not _context.Studies.
Thanks for your help.
So your result from studies is list of BundleNodeViewMode and you want to list the item from there. Then you should tell the selectlist what is the Id and Name you are displaying from.
ViewBag.studyList = new SelectList((from s in studies.OrderBy(p => p.StudyName), select new {Id = s.StudyId, Name = s.StudyName}) , "Id", "Name");
So I was working on a DropDown list and it works, but it has many duplicate emails, I just want to see distinct emails... So I tried doing .Distinct() in the model class, but that still gave me duplicates..
Model Class:
public string One_Manager_Email{ get; set; }
public List<Hello> getManagers()
{
var que = (from wr in db.View
select new Hello
{
O_Manager_Email= wr.One_Manager_Email
}).Distinct().ToList();
return que;
}
Controller Class: (This is probably where the problem is happening)
public ActionResult Index()
{
test = new Hello();
ViewBag.Managers = new SelectList(test.getManagers(), "", "O_Manager_Email");
return View(test.getStuff());
}
View Class:
<div>
#Html.DropDownList("Managers", ViewBag.Managers as SelectList)
</div>
Any help would be great, thank you!
You need to group your objects by the property you want them to be distinct by, and then select the first element of the grouping.
public List<Hello> getManagers()
{
var que = (from wr in db.View
select new Hello
{
O_Manager_Email= wr.One_Manager_Email
})
.GroupBy(g => g.O_Manager_Email) //group by property
.Select(g => g.First()) //take first element from every grouping
.ToList();
return que;
}
For some more details, you can see this post that has more details on grouping and distinct: LINQ's Distinct() on a particular property
Distinct won't work on objects like that, as objects are always distinct, but you can try using group by in your query, something along these lines:
var que = (from wr in db.View
group new {wr.One_Manager_Email}
by new {wr.One_Manager_Email} into grouped
select new Hello
{
O_Manager_Email= grouped.Key.One_Manager_Email
}).ToList();
return que;
If you just need email address, you can select just string instead of selecting Hello object. If you select Hello object and try to distinct you like that way, you obviously get duplicated items. Because every object is already unique.
I believe you have already answer. GroupBy might solve your problem. However unless you really need GroupBy, don't use GroupBy! It's really expensive operation.
In your case, you should use DistinctBy.
var distinctList = list.DistinctBy(x => x.Prop).ToList();
On your code:
var que = (from wr in db.View
select new Hello
{
O_Manager_Email = wr.One_Manager_Email
}).DistinctBy(x=>x.O_Manager_Email).ToList();
Oh, in terms of DistinctBy usage, you should import namespace of Microsoft.Ajax.Utilities.
using Microsoft.Ajax.Utilities;
I'm trying to create a WebGrid which has to be very dynamic. The columns are defined in a list, which I've done like so:
#{
List<WebGridColumn> columns = new List<WebGridColumn>();
foreach (var column in Model.Columns)
{
columns.Add(new WebGridColumn() { ColumnName = column.Name, Header = column.Name });
}
}
#grid.GetHtml(
columns: columns)
All well and good, but the problem I have is with the rows. I'll try and explain...
For this question let's say we have two columns for Name and Address.
I have a collection of row objects, lets say SearchResult objects. A SearchResult contains a Dictionary of any number of attributes, such as Name, Address, Phone, Height, Bra Size, or anything (think of the EAV pattern). I need to access the attributes based on Column Name.
I figured I could do this using format, but I can't seem to figure it out. I want something like this:
columns.Add(new WebGridColumn() { ColumnName = column.Name, Header =
column.Header, Format = #<text>#item.Attributes[column.Name]</text> });
This sort of works but despite creating the format for the separate columns, the rows get populated with only the last column's format. i.e.:
Name Address
1 Main Street 1 Main Street
45 Paradise Av 45 Paradise Av
etc
I think it should work if you leave out the "ColumnName" (superfluous anyway), and also make the dynamic expression a bit more explicit:
columns.Add(
new WebGridColumn() {
Header = column.Header,
Format = (item) => #Html.Raw("<text>" + #item.Attributes[column.Name] + "</text>")
}
);
This issue is related to reference variables. You need to have the Format property in terms of the other properties of the WebGridColumn. This is how I would do it:
#{
List<WebGridColumn> columns = new List<WebGridColumn>();
foreach (var column in Model.Columns)
{
var col = new WebGridColumn();
col.Header = column.Name;
col.Format = (item) => #Html.Raw("<text>" + #item.Attributes[col.Header] + "</text>");
columns.Add(col);
}
}
I am fairly new to SharePoint development and as you may all know that it is very basic for one to know how to access fields in a choice column...
My problem:
I want to access the values of the Check Boxes from a Choice Column.
For Example:
I have a document library called Libe, this document library has a custom column with type Choice and has 4 checkboxes with the values:
Category 1
Category 2
Category 3
Category 4
How do I get the values like literally the text values of what is in the Check Box List: "Category 1", "Category 2" ... "Category 4".
Any ideas?
I can access the column fine and get the selected values, I just do not know how to get the values the user can choose from.
Answer
SPFieldMultiChoice Fld = (SPFieldMultiChoice)list.Fields["Column"];
List<string> fieldList = new List<string>();
foreach (string str in Fld.Choices)
{
fieldList.Add(str);
}
Above is the answer, I can't answer my own question until I have a 100 rep.
using (SPSite site = new SPSite("http://servername/"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["ListName"];
string values = list["yourColumn"] as string;
string[] choices = null;
if (values != null)
{
choices = values.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
}
}
}
You can try this code for getting choice field value from document library.
I have a table that contains a list of EquipmentIDs and another table that has maintenance records.
When the user edits a maintenance record I want there to be a drop down list of all of the equipment IDs from the table.
The dropdown list populates, and it populates with the correct amount of entries, however they all say System.Web.MVC.SelectListItem instead of the value of the ID.
Here is the code that generates the list:
public ActionResult Edit(int id)
{
MaintPerformed maintPerformed = maintPerformedRepository.GetMaintPerformed(id);
IList<EquipmentID> IDs = equipmentIDRepository.GetEquipmentIDAsList();
IEnumerable<SelectListItem> selectEquipList =
from c in IDs
select new SelectListItem
{
//Selected = (c.EquipID == maintPerformed.EquipID),
Text = c.EquipID,
Value = c.Sort.ToString()
};
ViewData["EquipIDs"] = new SelectList(selectEquipList, maintPerformed.ID);
return View(maintPerformed);
}
Here is the entry in the .aspx page for the Dropdown list:
%: Html.DropDownList("EquipIDs") %>
Here is how I am generating the list from the table:
public List<EquipmentID> GetEquipmentIDAsList()
{
return db.EquipmentIDs.ToList();
}
It appears that everything is working correctly with the exception of assigning the text to be displayed in the drop down box.
What am I missing or not thinking correctly about?
SelectList and SelectListItem are actually mutually exclusive. You should be using one or the other. Etiher pass the constructor of SelectList your raw data (IDs) or don't use SelectList at all and just make ViewData["EquipIDs"] your enumerable of SelectListItem. If you go with the latter approach, you will have to tweak your code so that you are setting the selected item in the constructor of SelectListItem (as you had done, but commented out).
Either:
ViewData["EquipIDs"] = new SelectList(IDs, maintPerformed.ID, "EquipID", "Sort");
Or:
IEnumerable<SelectListItem> selectEquipList =
from c in IDs
select new SelectListItem
{
Selected = c.EquipID == maintPerformed.EquipID,
Text = c.EquipID,
Value = c.Sort.ToString()
};
ViewData["EquipIDs"] = selectEquipList;