How to take FirstName and LastName in DropDown List - c#

In controller I have this code and at this moment I have DropDown list just for firstname.
Code is here:
ViewBag.patnikID = new SelectList(db.tbl_patnici, "pID", "firstname");
And now I need some code like this:
ViewBag.patnikID = new SelectList(db.tbl_patnici, "pID", ("firstname" + "lastname"));
How to do it?

Your tbl_patnici class
public class tbl_patnici
{
public int pID { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
//[NotMapped] If you use entityframework then you must use NotMapped attribute.
public string fullname { get { return this.firstname + " " + this.lastname; } }
}
ViewBag.patnikID = new SelectList(db.tbl_patnici, "pID", "fullname");

I would suggest you don't bind directly to the database source and instead bind to your own IEnumerable which has the properties you want. I often have a reusable "ListItem" class which has ID and Text properties and then use a function to populate the list with the data I want.
For example:
Create a new class:
public class ListItem
{
public int ID { get; set; }
public string Text { get; set; }
}
Create a helper function:
public List<ListItem> GetList()
{
// get "db" here.
return db.tbl_patnici.Select(x => new ListItem {
ID = x.pID,
Text = x.firstname + " " + x.lastname
});
}
Call it like so:
ViewBag.patnikID = new SelectList(GetList(), "ID", "Text");

You can check this:
#Html.DropDownListFor(model => model.pID, new SelectList(db.tbl_patnici, "pID", Model.firstname + " " + Model.lastname, Model.pID), new { style = " width:260px" })

Related

SelectListItem is empty, if statement inside method shows it to be filled

error message:
http://prntscr.com/qtlodf
method:
public IActionResult GroepsResultaten(int vakId, int groepId)
{
var studentenLijst = _context.Student.Join(_context.StudentGroep,
s => s.Id,
sg => sg.StudentId,
(s, sg) => new { Student = s, StudentGroep = sg })
.Where(x => x.StudentGroep.GroepId == groepId)
.Select(x => x.Student);
ViewBag.Studenten = new SelectList(studentenLijst, "Id", "Naam");
return View();
}
I've also tried this:
public IActionResult GroepsResultaten(int vakId, int groepId)
{
var studentInfo = _context.Student
.Select(s =>
new
{
s.Id,
Naam = string.IsNullOrEmpty(s.Tussenvoegsel)
? s.Voornaam + " " + s.Achternaam + " - " + s.Studentnummer
: s.Voornaam + " " + s.Tussenvoegsel + " " + s.Achternaam + " - " + s.Studentnummer,
forStudent = s.Studentnummer + "-" + s.Achternaam
});
ViewBag.Studenten = new SelectList(studentInfo, "Id", "Naam");
return View();
}
I'm a bit stuck at this. I want to return multiple input fields (I'm just testing with selectlist at the moment) for all students of group x, from there on I want to be able to grade students for the subject that's included in the view using get method. Because English isn't my first language I've included two screenshots to clarify what I mean.
clarification of what I want to achieve:
group view: http://prntscr.com/qtlrqd
wireframe of method view: http://prntscr.com/qtlswn
models:
public class Student
{
public int Id { get; set; }
[Required]
public string Voornaam { get; set; }
[Required]
public string Achternaam { get; set; }
public string Tussenvoegsel { get; set; }
public string Studentnummer { get; set; }
public List<Resultaat> Resultaten { get; set; }
public List<StudentGroep> Groepen { get; set; }
}
public class Groep
{
public int Id { get; set; }
[Required]
public string Naam { get; set; }
[Required]
public string Groepscode { get; set; }
public List<GroepVak> Vakken { get; set; }
public List<StudentGroep> Studenten { get; set; }
}
public class StudentGroep
{
public Student Student { get; set; }
public int StudentId { get; set; }
public Groep Groep { get; set; }
public int GroepId { get; set; }
}
I hope I've included enough information, I'm available on discord too if that makes it easier.
The problem is what the SelectList class returns. Because view side results that ViewBag.Studenten is null.
Also, you must make sure that the database query returns a value.
Using ViewData resulted in what I want, from here on I can hopefully figure out how to use it for posting grades for each student.
Method:
public IActionResult GroepsResultaten(int vakId, int groepId)
{
var studentenLijst = _context.Student.Join(_context.StudentGroep,
s => s.Id,
sg => sg.StudentId,
(s, sg) => new { Student = s, StudentGroep = sg })
.Where(x => x.StudentGroep.GroepId == groepId)
.Select(x => x.Student)
.ToList();
if (groepId >= 1)
{
ViewData["Studenten"] = studentenLijst.ToList();
}
//ViewBag.Studenten = new SelectList(studentenLijst, "Id", "Naam");
return View();
}
View:
#foreach (var item in ViewBag.Studenten)
{
#item.Voornaam;
<input type="number" />
}

LINQ/C# - Making a DTO from a collection?

I'm using EF 6.2 with SQL. Suppose I have these DTO classes:
private class ParentModel
{
public string FullName { get; set; }
public IEnumerable<ChildModel> Children { get; set; }
}
private class ChildModel
{
public string FullName { get; set; }
public string SpiritAnimalDescription { get; set; }
}
ParentModel is derived from an entity class Parent.
ChildModel is from Child, which has a relationship with another entity class SpiritAnimal. Note that I changed it in the .EDMX to Children.
As you can infer, SpiritAnimal has a Description field which I'm trying to retrieve into the ChildModel field, SpiritAnimalDescription.
Naturally, a Parent has a collection of Child, which in turn has one SpiritAnimal (by design). Now, I'm trying to obtain a List<ParentModel> with this code, which currently isn't working:
var query = from p in db.Parents
join c in db.Children on p.Id equals c.Parent_Id
join sa in db.SpiritAnimals on c.SpiritAnimal_Id equals sa.Id
select new ParentModel
{
FullName = p.LastName + ", " + p.FirstName
Children = c.Select(a => new ChildModel // <-- Error here :(
{
FullName = a.FirstName + " " + a.LastName,
SpiritAnimalDescription = sa.Description
}
};
var list = query.ToList();
How can I solve this, as efficiently as possible? Thanks!
EDIT:
Entity classes look something like this, for brevity:
private class Parent
{
public int Id { get; set; } // PK
public string LastName { get; set; }
public string FirstName { get; set; }
}
private class Child
{
public int Id { get; set; } // PK
public string LastName { get; set; }
public string FirstName { get; set; }
public int Parent_Id { get; set; } // FK
public int SpiritAnimal_Id { get; set; } // FK
}
private class SpiritAnimal
{
public int Id { get; set; } // PK
public string Description { get; set; }
}
Your code cannot be compiled and run, so it is impossible to determine exactly what should be.
I can only assume that it should be something like this:
var query = from p in db.Parents
select new ParentModel
{
FullName = p.LastName + ", " + p.FirstName,
Children = db.Children.Where(c => c.Parent_Id == p.Id)
.Select(c => new ChildModel
{
FullName = c.FirstName + " " + c.LastName,
SpiritAnimalDescription = db.SpiritAnimals
.FirstOrDefault(sa => sa.Id == c.SpiritAnimal_Id).Description
})
};
Note: use the navigation properties.
Should look something like this:
var query = from p in db.Parents
select new ParentModel()
{
FullName = p.LastName + ", " + p.FirstName,
Children = p.Clildren.Select(a => new ChildModel()
{
FullName = a.FirstName + " " + a.LastName,
SpiritAnimalDescription = sa.Description
}).ToList()
};

MVC5 Razor html.dropdownlistfor set selected when value is in array

I'm developing an ASP.NET MVC 5 application, with C# and .NET Framework 4.6.1.
I have this View:
#model MyProject.Web.API.Models.AggregationLevelConfViewModel
[...]
#Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, (SelectList)Model.HelperCodeTypeItems, new { id = "Configurations[0].HelperCodeType" })
The ViewModel is:
public class AggregationLevelConfViewModel
{
private readonly List<GenericIdNameType> codeTypes;
private readonly List<GenericIdNameType> helperCodeTypes;
public IEnumerable<SelectListItem> CodeTypeItems
{
get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
public int ProductionOrderId { get; set; }
public string ProductionOrderName { get; set; }
public IList<Models.AggregationLevelConfiguration> Configurations { get; set; }
public AggregationLevelConfViewModel()
{
// Load CodeTypes to show it as a DropDownList
byte[] values = (byte[])Enum.GetValues(typeof(CodeTypes));
codeTypes = new List<GenericIdNameType>();
helperCodeTypes = new List<GenericIdNameType>();
for (int i = 0; i < values.Length; i++)
{
GenericIdNameType cType = new GenericIdNameType()
{
Id = values[i].ToString(),
Name = EnumHelper.GetDescription((CodeTypes)values[i])
};
if (((CodeTypes)values[i]) != CodeTypes.NotUsed)
codeTypes.Add(cType);
helperCodeTypes.Add(cType);
}
}
}
And Models.AggregationLevelConfiguration is:
public class AggregationLevelConfiguration
{
public byte AggregationLevelConfigurationId { get; set; }
public int ProductionOrderId { get; set; }
public string Name { get; set; }
public byte CodeType { get; set; }
public byte HelperCodeType { get; set; }
public int PkgRatio { get; set; }
public int RemainingCodes { get; set; }
}
I need to set selected value in these properties:
public IEnumerable<SelectListItem> CodeTypeItems
{
get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
But I can't set it in new SelectList(codeTypes, "Id", "Name"); or new SelectList(helperCodeTypes, "Id", "Name"); because the selected value are in Configurations array: fields AggregationLevelConfiguration.CodeType and AggregationLevelConfiguration.HelperCodeType.
I think I have to set selected value in the View, but I don't know how to do it.
How can I set the selected values?
Unfortunately #Html.DropDownListFor() behaves a little differently than other helpers when rendering controls in a loop. This has been previously reported as an issue on CodePlex (not sure if its a bug or just a limitation)
The are 2 option to solve this to ensure the correct option is selected based on the model property
Option 1 (using an EditorTemplate)
Create a custom EditorTemplate for the type in the collection. Create a partial in /Views/Shared/EditorTemplates/AggregationLevelConfiguration.cshtml (note the name must match the name of the type
#model yourAssembly.AggregationLevelConfiguration
#Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])
.... // other properties of AggregationLevelConfiguration
and then in the main view, pass the SelectList to the EditorTemplate as additionalViewData
#using (Html.BeginForm())
{
...
#Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems })
...
Option 2 (generate a new SelectList in each iteration and set the selectedValue)
In this option your property CodeTypeItems should to be IEnumerable<GenericIdNameType>, not a SelectList (or just make codeTypes a public property). Then in the main view
#Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, new SelectList(Model.CodeTypeItems, "Id", "Name", Model.Configurations[0].HelperCodeType)
Side note: there is no need to use new { id = "Configurations[0].HelperCodeType" - the DropDownListFor() method already generated that id attribute
I wrote this class to overcome an issue I was having with selecting an option in an html select list. I hope it helps someone.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Login_page.Models
{
public class HTMLSelect
{
public string id { get; set; }
public IEnumerable<string> #class { get; set; }
public string name { get; set; }
public Boolean required { get; set; }
public string size { get; set; }
public IEnumerable<SelectOption> SelectOptions { get; set; }
public HTMLSelect(IEnumerable<SelectOption> options)
{
}
public HTMLSelect(string id, string name)
{
this.id = id;
this.name = name;
}
public HTMLSelect(string id, string name, bool required, IEnumerable<SelectOption> options)
{
this.id = id;
this.name = name;
this.required = required;
}
private string BuildOpeningTag()
{
StringBuilder text = new StringBuilder();
text.Append("<select");
text.Append(this.id != null ? " id=" + '"' + this.id + '"' : "");
text.Append(this.name != null ? " name=" + '"' + this.name + '"' : "");
text.Append(">");
return text.ToString();
}
public string GenerateSelect(IEnumerable<SelectOption> options)
{
StringBuilder selectElement = new StringBuilder();
selectElement.Append(this.BuildOpeningTag());
foreach (SelectOption option in options)
{
StringBuilder text = new StringBuilder();
text.Append("\t");
text.Append("<option value=" + '"' + option.Value + '"');
text.Append(option.Selected != false ? " selected=" + '"' + "selected" + '"' + ">" : ">");
text.Append(option.Text);
text.Append("</option>");
selectElement.Append(text.ToString());
}
selectElement.Append("</select");
return selectElement.ToString();
}
}
public class SelectOption
{
public string Text { get; set; }
public Boolean Selected { get; set; }
public string Value { get; set; }
}
}
And
public IEnumerable<SelectOption> getOrderTypes()
{
List<SelectOption> orderTypes = new List<SelectOption>();
if (this.orderType == "OptionText")
{
orderTypes.Add(new SelectOption() { Value = "1", Text = "OptionText", Selected = true });
} else
{
orderTypes.Add(new SelectOption() { Value = "2", Text = "OptionText2" });
}
}
And to use it:
#{
Login_page.Models.HTMLSelect selectElement = new Login_page.Models.HTMLSelect("order-types", "order-types");
}
#Html.Raw(selectElement.GenerateSelect(Model.getOrderTypes()));
I leave this in case it helps someone else. I had a very similar problem and none of the answers helped.
We had in a view this line at the top:
IEnumerable<SelectListItem> exitFromTrustDeed = (ViewData["ExitFromTrustDeed"] as IEnumerable<string>).Select(e => new SelectListItem() {
Value = e,
Text = e,
Selected = Model.ExitFromTrustDeed == e
});
and then below in the view:
#Html.DropDownListFor(m => m.ExitFromTrustDeed, exitFromTrustDeed, new { #class = "form-control" })
We had a property in my ViewData with the same name as the selector for the lambda expression and for some reason that makes the dropdown to be rendered without any option selected.
We changed the name in ViewData to ViewData["ExitFromTrustDeed2"] and that made it work as expected.
Weird though.

Drop down list in MVC from DB text, value

I have problem with dropdownlist. I want show text in selectedlist but select Id.
How I implement view? In view I must save selected data to model (odbiorca)
Controller:
var odbiorca = dbU.Uczniowie.OrderBy(d => d.Nazwisko).Select(m => m.Nazwisko + " " + m.Imie).ToList(); //return Names
var odbiorcaId= dbU.Uczniowie.OrderBy(d => d.Id).Select(m => m.Nazwisko + " " + m.Imie).ToList(); //return IDs
List<SelectListItem> items = new List<SelectListItem>();
for (int i=0;i<dbU.Uczniowie.Count();i++)
{
items.Add(new SelectListItem { Text = odbiorca[i], Value = odbiorcaId[i] });
}
ViewBag.odbiorca = items;
Model:
public class Uwaga
{
[Key]
[Required]
public string Id { get; set; }
[Required]
public string odbiorca { get; set; }
[Required]
public DateTime data { get; set; }
}
I tried this solution but the program saves text, but not value.
#Html.DropDownList("odbiorca", "----")
Both of your linq statements return the same values.
var odbiorca = dbU.Uczniowie.OrderBy(d => d.Nazwisko).Select(m => m.Nazwisko + " " + m.Imie).ToList(); //return Names
var odbiorcaId= dbU.Uczniowie.OrderBy(d => d.Id).Select(m => m.Nazwisko + " " + m.Imie).ToList(); //return IDs
both of these return a list of m.Nazwisko + " " + m.Imie there is no Id.
you should just use one query to get your select list
var list = dbU.Uczniowie.Select(a => new {Text= a.Nazwisko + " " + a.Imie, Value = a.Id}).ToList();
ViewBag.odbiorca = list.Select(a => new SelectListItem{ Text = a.Text, Value = a.Value.ToString()});
Try this approach. Lets take your model class:
public class Uwaga
{
[Key]
[Required]
public string Id { get; set; }
Required]
public string odbiorca { get; set; }
[Required]
public DateTime data { get; set; }
}
In the view you can use the same helper: #Html.DropDownList("odbiorca", "----")
But, in the controller you set the "id" and "text" columns through a SelectList object. Take the example in the default action in the controller:
public ActionResult Index()
{
//Creates a example list with multiple "Uwaga" items,
//but you might want to pull the data from the database
List<Uwaga> UwagaList = new List<Uwaga>();
for (int i = 1; i <= 10; i++)
{
Uwaga item = new Uwaga();
item.Id = i;
item.odbiorca = "odbiorca " + i;
UwagaList.Add(item);
}
//Create a SelectList object, the first parameter is the list created above.
//The second parameter is the "id" key and the thirth
//parameter is the text you want to display in the dropdown.
var SelectList = new SelectList(UwagaList, "Id", "odbiorca");
//Fill the dropdownlist "odbiorca" using ViewData.
ViewData["odbiorca"] = SelectList;
}
I hope it helps.

How to show only part of text in CheckedListBox

I'm creating an WindowsForms application that is using a list of persons with 4 parameters (ID, Name, Surname, Permissions):
public List<Osoba> ListaOsoba()
{
Osoba nr1 = new Osoba(1, "Name", "Surname", Permissions.Administrator);
Osoba nr2 = new Osoba(2, "Name2", "Surname2", Permissions.Użytkownik);
Osoba nr3 = new Osoba(3, "Name3", "Surname3", Permissions.Użytkownik);
listaOsób.Add(nr1);
listaOsób.Add(nr2);
listaOsób.Add(nr3);
return listaOsób;
}
I would like to post all those Parameters to CheckedListBox, but show only name and surname to the user. The ID and Permissions should be hidden, but they need to exist, because I want to use them later.
Every help will be appreciated.
public static bool CheckBoxListPopulate(CheckBoxList CbList, IList<T> liSource, string TextFiled, string ValueField)
{
try
{
CbList.Items.Clear();
if (liSource.Count > 0)
{
CbList.DataSource = liSource;
CbList.DataTextField = TextFiled;
CbList.DataValueField = ValueField;
CbList.DataBind();
return true;
}
else { return false; }
}
catch (Exception ex)
{ throw ex; }
finally
{
}
}
here Cb list is the control name and
List item Ilist is the list source name
Text field (should be concatination ) ="Name" + "Surname"
Value field will be Hidden it can be "1,2,3"
so only Text field will be visible to user
To bind only name and surname to checkedboxlist first store name and surname together and then try this:
NameS = "Name" + "Surname";
((ListBox)checkedListBox).DataSource = listaOsób;
((ListBox)checkedListBox).DisplayMember = "NameS";
try this, here you have to make arbitrary compound properties for display and value member like DisplayName and HiddenId and then you can easily bound with checkedlistbox.
public class Osoba
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Permissions Permission { get; set; }
public string DisplayName { get; set; }
public string HiddenId { get; set; }
public Osoba()
{ }
public Osoba(int id, string fname, string lname, Permissions p)
{
Id = id;
FirstName = fname;
LastName = lname;
Permission = p;
DisplayName = FirstName + " " + LastName;
HiddenId = Id + "_" + Permission.GetHashCode();
}
public void ListaOsoba()
{
List<Osoba> objList = new List<Osoba>();
Osoba nr1 = new Osoba(1, "Name", "Surname", Permissions.Administrator);
Osoba nr2 = new Osoba(2, "Name2", "Surname2", Permissions.Uzytkownik);
Osoba nr3 = new Osoba(3, "Name3", "Surname3", Permissions.Uzytkownik);
objList.Add(nr1);
objList.Add(nr2);
objList.Add(nr3);
((ListBox)checkedListBox1).DataSource = objList;
((ListBox)checkedListBox1).DisplayMember = "DisplayName";
((ListBox)checkedListBox1).ValueMember = "HiddenId";
MessageBox.Show(((ListBox)checkedListBox1).Text);
MessageBox.Show(((ListBox)checkedListBox1).SelectedValue.ToString());
}
}
public enum Permissions
{
Administrator,
Uzytkownik
}
I had a similar thing with SQL. I returned many columns, but only wanted one to show.
Anyway
ArrayList arr = new ArrayList();
foreach (object o in ListaOsoba)
{
arr.Items.Add(o[1].ToString()+" "+o[2].ToString());
}
foreach (var item in arr)
{
chkNames.Items.Add(arr.ToString()); //chkNames is your CheckListBox
}
Then later when querying which ID and such goes where, loop through you original list, and see who was ticked based on the name and surname combo, find the ID related to that person and you should be sorted

Categories

Resources