Checkboxes for attribute list - asp.net-mvc

I am new to ASP.NET and web programming in global.
I'm trying to make web application for job applications. I've managed to save applicant name, mail etc. but now I'm having troubles with checkboxes. Every applicant should have Skills property which contains list of applicants skills (like Java, JavaScript etc.).
In my form there should be checkbox for every skill but I can't achieve that.
I have this so far:
My model:
public class Applicant
{
[Key]
public int ID { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public string Email { get; set; }
[DataType(DataType.MultilineText)]
public string Letter { get; set; }
[EnumDataType(typeof(Sex))]
public Sex Gender { get; set; }
[EnumDataType(typeof(Pos))]
public Pos Position { get; set; }
public enum Sex
{
[Display(Name = "Male")] Male = 1,
[Display(Name = "Female")] Female = 2
}
public enum Pos
{
[Display(Name = "Front-end")] Frontend = 1,
[Display(Name = "Back-end")] Backend = 2,
[Display(Name = "Tester")] Tester = 3,
[Display(Name = "System administrator")] SysAdmin = 4,
[Display(Name = "Project manager")] ProjMan = 5,
[Display(Name = "Database specialist")] Database = 6,
}
[Display(Name = "Candidate skills: ")]
public List<Skills> SkillList { get; set; }
public static List<Skills> getSkills()
{
List<Skills> skills = new List<Skills>()
{
new Skills() { ID = 1, skillName = "Java", isChecked = false },
new Skills() { ID = 2, skillName = "JavaScript", isChecked = false },
new Skills() { ID = 3, skillName = "PHP", isChecked = false },
};
return skills;
}
}
public class Skills
{
[Key]
public int ID { get; set; }
public string skillName { get; set; }
public bool isChecked { get; set; }
}
In controller I get error
" Cannot implicitly convert type
'System.Collections.Generic.List jobAppForm.Models.Skills ' to
'System.Collections.Generic.List jobAppForm.Models.Applicant ' "
My controller:
// GET
public ActionResult Create()
{
List<Applicant> model = new List<Applicant>();
model = Applicant.getSkills();
return View(model);
}
So I have Create view which contains textboxes for FName, LName.... and dropdownlist for Gender and Position.
What I can't figure out is how to display checkboxes for every skill and save data to database.

Assuming your Skill class contains a name and a boolean property, and assuming you are using Razor for your view, you create a list of checkbox form fields all with a common "name" property but each one includes an index such as name="myname[0]". When you post the form your controller gets an array of values for "myname" you iterate through.
#for (int i = 0; i < Model.SkillList.Count(); i++)
{
string checkedValue = "false";
#if (Model.SkillList[i])
{
checkedValue = "checked";
}
#Html.CheckBox("myname[" + i.ToString() + "]", new { #checked = checkedValue })
}
Note: when you process the posted values an unchecked box value will be "false" and a checked box will be "true, false" so be careful to interpret the value as myname[i] != "false".

Try:
#for(int i = 0;i < Model.SkillList.Count;i++)
{
#Html.CheckBoxFor(model => model.SkillList[i].IsSelected)
#Html.DisplayFor(model => model.SkillList[i].skillName)
}

Related

How to display the details of a row from multiple tables using LINQ?

I'm stuck here on a situation wherein I should display the details of a person together with the list of his/her allocations. I've done creating a view model to pass the data to a view but the result is:
The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery`1[EKCMIDTA.ViewModels.EmployeeDetailsVM]', but this dictionary requires a model item of type 'EKCMIDTA.ViewModels.EmployeeDetailsVM'.
For the TicketScannings table, I just wanted to know whether the person has used some of the allocations, and to count how many were used, regardless it it's null.
I hope someone can help me with this.
Thanks!
Controller:
public ActionResult GetDetails(int empId)
{
var employeeInformation = identityContext.AspNetUsers.Find(empId);
var employeeDetails = dbContext.TicketAllocations.Include(a => a.AllocationCategory).Where(t => t.CMId == empId).ToList();
var query = (from alloc in dbContext.TicketAllocations
join scan in dbContext.TicketScannings
on alloc.Id equals scan.TicketAllocationId
join card in dbContext.CardNumberAssignments
on alloc.CMId equals card.CMId into a
from card in a.DefaultIfEmpty()
join reserve in dbContext.ReservedCardNumbers
on card.CardNumberId equals reserve.Id into b
from reserve in b.DefaultIfEmpty()
where (alloc.CMId == empId)
select new EmployeeDetailsVM()
{
Employee = new Employee()
{
FirstName = employeeInformation.FirstName,
LastName = employeeInformation.LastName,
CMId = employeeInformation.Id,
CardNumber = reserve == null ? "No Card Number yet" : reserve.CardNumber,
QRCode = card == null ? "No QR Code yet" : card.QRCode
},
GetTicketAllocations = employeeDetails
});
return View(query);
View Model:
public class EmployeeDetailsVM
{
public Employee Employee { get; set; }
public IEnumerable<Allocation> GetTicketAllocations { get; set; }
}
public class Employee
{
public string CMId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string CardNumber { get; set; }
public string QRCode { get; set; }
}
public class Allocation
{
public int AllocationId { get; set; }
public string AllocationName { get; set; }
public int Quantity { get; set; }
public bool IsActive { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public string ModifiedBy { get; set; }
public DateTime ModifiedDate { get; set; }
}
View:
#model EKCMIDTA.ViewModels.EmployeeDetailsVM
Looks like your view is only accepting a model of a single EmployeeDetailsVM, but you're passing in a query which would could return multiple.
so you can change #model EKCMIDTA.ViewModels.EmployeeDetailsVM to #model IEnumerable<EKCMIDTA.ViewModels.EmployeeDetailsVM>
or change your GetDetails action to return View(query.FirstOrDefault());
Edit based on comment
public ActionResult GetDetails(int empId)
{
var employeeInformation = identityContext.AspNetUsers.Find(empId);
var employeeTickets = dbContext.TicketAllocations.Include(a => a.AllocationCategory).Where(t => t.CMId == empId).ToList();
var employeeDetails = (from alloc in dbContext.TicketAllocations
join scan in dbContext.TicketScannings
on alloc.Id equals scan.TicketAllocationId
join card in dbContext.CardNumberAssignments
on alloc.CMId equals card.CMId into a
from card in a.DefaultIfEmpty()
join reserve in dbContext.ReservedCardNumbers
on card.CardNumberId equals reserve.Id into b
from reserve in b.DefaultIfEmpty()
where (alloc.CMId == empId)
select new EmployeeDetailsVM()
{
Employee = new Employee()
{
FirstName = employeeInformation.FirstName,
LastName = employeeInformation.LastName,
CMId = employeeInformation.Id,
CardNumber = reserve == null ? "No Card Number yet" : reserve.CardNumber,
QRCode = card == null ? "No QR Code yet" : card.QRCode
}
}).FirstOrDefault();
if (employeeDetails != null)
employeeDetails.GetTicketAllocations = employeeTickets;
return View(employeeDetails);
}

2 models with one to many relationship - How to list the count of items in the first model

I had a tough time coming up with a good title. I am working on an MVC application using asp.net and Entity Framework. I have 2 models, Categories and Products. There can be many products in each category. I have a page that lists out each category and each product with the associated fields for each. I want to add a column(field) to the Category list that lists how many products are in that category. I have no idea how to go about doing this. I am guessing I will need to add an additional variable to the Categories model called "productCount" or something like that.
Category model:
public class CategoryModel
{
public int ID { get; set; }
[Required(ErrorMessage = "Required")]
[Display(Name = "Category Name")]
[MaxLength(50)]
public String categoryName { get; set; }
[DefaultValue(true)]
[Display(Name = "Active?")]
public bool isActive { get; set; }
}
Product model:
public class ProductModel
{
public int ID { get; set; }
[Required(ErrorMessage = "Required")]
[Index("ItemNumber", 1, IsUnique = true)]
[Display(Name = "Item #")]
public int itemNumber { get; set; }
[Required(ErrorMessage = "Required")]
[Display(Name = "Product")]
[MaxLength(50)]
public String product { get; set; }
[Required(ErrorMessage = "Required")]
[Display(Name = "Description")]
[MaxLength(500)]
public String description { get; set; }
[DefaultValue(true)]
[Display(Name = "Active?")]
public bool active { get; set; }
[Display(Name = "Image Name")]
public String imageName { get; set; }
[Display(Name = "PDF Name")]
public String PDFName { get; set; }
[ForeignKey("Category")]
public int CategoryID { get; set; }
public virtual CategoryModel Category { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
public static IEnumerable<SelectListItem> getCategories()
{
using (var db = new ProductContext())
{
List<SelectListItem> list = new List<SelectListItem>();
var x = db.Categories.ToList();
foreach (var y in x)
{
list.Add(new SelectListItem { Value = y.ID.ToString(), Text = y.categoryName });
}
return list;
}
}
}
Admin Model:
public class AdminModel
{
public IEnumerable<CategoryModel> Categories { get; set; }
public IEnumerable<ProductModel> Products { get; set; }
public RegisterViewModel RegisterUsers { get; set; }
}
And here is the Controller method that lists the categories:
public ActionResult ControlPanel()
{
ViewBag.Message = TempData["Message"] == null ? "" : TempData["Message"].ToString();
//using (var db = new )
using (var db = new ProductContext())
{
var categories = from c in db.Categories
select c;
categories = categories.OrderByDescending(c => c.isActive);
var model = new AdminModel
{
Categories = categories.ToList(),
Products = db.Products.ToList()
};
return View(model);
}
}
For a single categoryID you can just use Linq's Count():
int specificCategoryID = 15;
return db.Products.Where(w => w.CategoryID == specificCategoryID).Count();
For a list of key/value pairs of categoryIDs and the count of products, something like this:
var products = db.Products.AsEnumerable();
var productCount = products.GroupBy(p => p.CategoryID,
(k, v) => new { CategoryID = k, ProductCount = v.Count() });
I would recommend using a proper viewmodel and making sure that it only uses one query so you dont run into a select n+1 issue.
Edit:
Assuming you always have a list of all categories and products you can just do the calculation in the Admin ViewModel on the items you already pulled from the DB:
public class AdminModel
{
public IEnumerable<CategoryModel> Categories { get; set; }
public IEnumerable<ProductModel> Products { get; set; }
public RegisterViewModel RegisterUsers { get; set; }
public int GetProductCountForCategoryID(int categoryID)
{
return this.Products
.Count(w => w.CategoryID == categoryID);
}
}
Then in the view, just pass in whatever category ID like this:
#Model.GetProductCountForCategoryID(categoryID);

how to get data from multiple related tables and pass it to the view mvc

i have three table in my data base category and Subcategory and product:
category has many Subcategory
Subcategory has many product
so i'm trying to join this three table to get the data for each product and display it in a view like that:
public ActionResult Index()
{
var memberId = WebSecurity.CurrentUserId;
var productsCompany = db.Products
.Join(db.SubCategorys, p => p.SubCategoryID, subcat => subcat.SubCategoryID,
(p, subcat) => new { p = p, subcat = subcat })
.Join(db.Categorys, temp0 => temp0.subcat.CategoryID, cat => cat.CategoryID,
(temp0, cat) => new { temp0 = temp0, cat = cat })
.Join(db.Sizes, temp1 => temp1.temp0.p.SizeID, s => s.SizeID,
(temp1, s) => new { temp1 = temp1, s = s })
.Join(db.Colors, temp2 => temp2.temp1.temp0.p.ColorID, c => c.ColorID,
(temp2, c) => new { temp2 = temp2, c = c })
.Join(db.Stores, temp3 => temp3.temp2.temp1.temp0.p.StoreID, st => st.StoreID,
(temp3, st) => new { temp3 = temp3, st = st })
.Join(db.Companyies, temp4 => temp4.st.CompanyID, camp => camp.CompanyID,
(temp4, camp) => new { temp4 = temp4, camp = camp })
.Where(temp5 => (temp5.camp.UserID == memberId))
.Select(temp5 => new
{
CategoryName = temp5.temp4.temp3.temp2.temp1.cat.CategoryName,
SubCategoryName = temp5.temp4.temp3.temp2.temp1.temp0.subcat.SubCategoryName,
ProductImageURL = temp5.temp4.temp3.temp2.temp1.temp0.p.ProductImageURL,
ProductName = temp5.temp4.temp3.temp2.temp1.temp0.p.ProductName,
Price = temp5.temp4.temp3.temp2.temp1.temp0.p.Price,
SizeName = temp5.temp4.temp3.temp2.s.SizeName,
ColorName = temp5.temp4.temp3.c.ColorName,
Quantity = temp5.temp4.temp3.temp2.temp1.temp0.p.Quantity,
Sales = temp5.temp4.temp3.temp2.temp1.temp0.p.Sales,
Discount = temp5.temp4.temp3.temp2.temp1.temp0.p.Discount,
StoreName = temp5.temp4.st.StoreName,
CompanyName = temp5.camp.CompanyName
}).ToList();
return View(productsCompany);
}
but in this way it take time to get the data so i' trying another way like that:
public ActionResult Index()
{
var memberId = WebSecurity.CurrentUserId;
var productsCompany = db.Products.Include(p => p.Color).Include(p => p.Size).Include(p => p.Store).Include(p => p.SubCategory);
return View(productsCompany.ToList());
}
but i cant figure out how can i get the data from the threed table category in this way and this only for display the data in this index view any idea on how can i create a new product from this three tables and thanks for any help
Update my classes is:
Product class
public class Product
{
[ScaffoldColumn(false)]
public int ProductID { get; set; }
[DisplayName("Image URL")]
//[DataType(DataType.Url)]
public string ProductImageURL { get; set; }
[Required(ErrorMessage = "Product Name is required")]
[DisplayName("Product Name")]
[StringLength(40)]
public string ProductName { get; set; }
[Required(ErrorMessage = "Price is required")]
[DisplayName("Product Price")]
[DataType(DataType.Currency)]
[Range(1, 5000.00, ErrorMessage = "Price must be between 1 SP and 5000.00 SP")]
public decimal Price { get; set; }
[Required(ErrorMessage = "Quantity is required")]
[DisplayName("Product Quantity")]
public int Quantity { get; set; }
[DisplayName("Sales Amount")]
[Range(0, 100, ErrorMessage = "sale Prsent must be between 1 and 100")]
public int Sales { get; set; }
//Exclude
public decimal Discount { get; set; }
[Required(ErrorMessage = "Color is required")]
[DisplayName("Color")]
public int ColorID { get; set; }
public virtual Color Color { get; set; }
[Required(ErrorMessage = "Size is required")]
[DisplayName("Size Type")]
public int SizeID { get; set; }
public virtual Size Size { get; set; }
[Required(ErrorMessage = "Store is required")]
[DisplayName("Store")]
public int StoreID { get; set; }
public virtual Store Store { get; set; }
[Required(ErrorMessage = "Category Type is required")]
[DisplayName("Sub Category Type")]
public int SubCategoryID { get; set; }
public virtual SubCategory SubCategory { get; set; }
}
Subcategory class:
public class SubCategory
{
[ScaffoldColumn(false)]
public int SubCategoryID { get; set; }
[Required(ErrorMessage = "Category Type is required")]
[DisplayName("Category Type")]
[StringLength(40)]
public string SubCategoryName { get; set; }
[Required(ErrorMessage = "Category is required")]
[DisplayName("Category")]
public int CategoryID { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
Category class:
public class Category
{
[ScaffoldColumn(false)]
public int CategoryID { get; set; }
[Required(ErrorMessage = "Category Name is required")]
[DisplayName("Category Name")]
[StringLength(50)]
public string CategoryName { get; set; }
public virtual ICollection<SubCategory> SubCategorys { get; set; }
}
Assuming that your category, sub category and product table are relate with forign key
If you are using Entity Framework to access the data from database and ProxyCreationEnabled is set to true (by default it is true) in your dbContext class constructor, The product table will automatically retrieve the related category and subcategory data for the specific product.
For example:
Product objProduct = _datacontext.Product.where(p=> p.productId.equals(pid));
and your Product table is defined as below:
public class Product
{
public int productId {get; set;}
...
public virtual IEnumarable<Category> pCategories {get; set;}
public virtual IEnumarable<SubCategory> pSubCategories {get; set;}
}
so now your objProduct will automatically store the related Category and SubCategory in pCategories and pSubCategories respectively. you can access it directly, No need to Join or Inclue the related tables explicitly.
Now pass the object to the view as a Model
public ActionResult Index()
{
Product objProduct = _datacontext.Product.SingleOrDefault(p=> p.productId.equals(pid));
return View(objProduct);
}
and use the Model in the view as per requirement.

Model value not accessable

I have a model which holds some details about an account (Name, Id etc) and then it has a type called Transaction, which holds information about the currently selected account transaction. A transaction can then have many transaction lines. So I have a List<TransactionsLine> property.
I am trying to set the value of a Drop down list, using the model, the value being in the List<> property. At the moment, there can, and must, only be one item in the list.
#Html.DropDownListFor(x=>x.Transaction.TransactionLines[0].CategoryId, Model.TransactionReferences.Categories, new {#onchange="populateSubCategory()"})
However, when I run this, the list defaults to the first item in the list.
In debug mode, when I hover the mouse over x.Transaction.TransactionLines[0].CategoryId, it doesn't show me a value. But when hover over the collection, Model.TransactionReferences.Categories, I see it has a valid list. It just won't set the selected value.
Am I doing this wrong?
It works in other drop downs I use, BUT the select value is in the top most level of my model:
#Html.DropDownListFor(x => x.Transaction.ThirdPartyId, Model.TransactionReferences.ThirdParties, new { #class = "cmbThirdParty form-control", #onchange = "populateDefaults()" })
That one works fine.
Note, doing it manually, works:
<select class="form-control" id="cmbCategory" onchange="populateSubCategory()">
<option value="0">Select a One</option>
#foreach (var cat in Model.TransactionReferences.Categories)
{
//var selected = cat.Value == Model.Transaction.TransactionLines[0].CategoryId.ToString() ? "selected" : "";
<option value="#cat.Value">#cat.Text</option>
}
</select>
But doesn't feel like the best way to do it.
Model:
The main model passed to the view:
public class TransactionModel
{
public int BankAccountId { get; set; }
public string BankAccountName { get; set; }
public TransactionContainer Transaction { get; set; }
public TransactionReferenceModel TransactionReferences { get; set; }
public DateTime DefaultDate { get; set; }
}
The TransactionReferenceModel holds all my 'reference' data used to populate drop down lists:
public class TransactionReferenceModel
{
public List<SelectListItem> TransactionTypes { get; set; }
public List<SelectListItem> EntryTypes { get; set; }
public List<SelectListItem> SubCategories { get; set; }
public List<SelectListItem> Categories { get; set; }
public List<SelectListItem> ThirdParties { get; set; }
public List<SelectListItem> CostCentres { get; set; }
}
The TransactionContainer model holds allthe main details about the selected transaction:
public class TransactionContainer
{
public int Id { get; set; }
public int AccountId { get; set; }
public int TransactionTypeId { get; set; }
public string TransactionType { get; set; }
public int EntryTypeId { get; set; }
public string EntryType { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/dd/yyyy}")]
public DateTime TransactionDate { get; set; }
public string ThirdParty { get; set; }
public int ThirdPartyId { get; set; }
public string Account { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "C2")]
public decimal Amount { get; set; }
public string Notes { get; set; }
public string CategoryDisplay { get; set; }
public string CostCentreDisplay { get; set; }
public decimal RunningBalance { get; set; }
public List<TransactionLine> TransactionLines { get; set; }
}
That then holds a list of transaction lines that make up the transaction. The transaction line holds the property I am trying to set the drop down to, which is CategoryId:
public class TransactionLine
{
public int Id { get; set; }
public int TransactionId { get; set; }
public int? CostCentreId { get; set; }
public string CostCentre { get; set; }
public int SubCategoryId { get; set; }
public string SubCategory { get; set; }
public int CategoryId { get; set; }
public string Category { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "C2")]
public decimal Amount { get; set; }
public string Notes { get; set; }
}
And here is how I am populating my model and sending it to the view:
public ActionResult EditTransaction(int? transactionId, int? bankAccountId)
{
// Create the main view object
var model = new TransactionModel
{
Transaction = new TransactionContainer
{
TransactionLines = new List<TransactionLine>()
}
};
if (transactionId != null) // This is an Edit, as opposed to an Add
{
var item = new TransactionService(currentUserId).GetTransaction(transactionId.Value);
// Populate the Reference object used to populate drop downs.
model.TransactionReferences = PopulateReferenceDate(model.TransactionReferences, item.TransactionLines[0].SubCategoryId);
model.BankAccountId = item.AccountId;
model.BankAccountName = item.Account.FullName;
model.DefaultDate = Session["DefaultDate"] != null
? DateTime.Parse(Session["DefaultDate"].ToString())
: DateTime.UtcNow;
model.Transaction.AccountId = item.AccountId;
model.Transaction.Amount = item.Amount;
model.Transaction.TransactionLines.Add(new TransactionLine
{
Id = item.TransactionLines[0].Id,
CategoryId = item.TransactionLines[0].SubCategory.CategoryId,
CostCentreId = item.TransactionLines[0].CostCentreId,
Notes = item.TransactionLines[0].Notes,
Amount = item.TransactionLines[0].Amount,
SubCategoryId = item.TransactionLines[0].SubCategoryId,
TransactionId = model.Transaction.Id
});
model.Transaction.EntryTypeId = item.EntryTypeId;
model.Transaction.Id = transactionId.Value;
model.Transaction.Notes = item.Notes;
model.Transaction.ThirdPartyId = item.ThirdPartyId;
model.Transaction.TransactionDate = item.TransactionDate;
model.Transaction.TransactionTypeId = item.TransactionTypeId;
}
else
{
// Populate the bank account details
var bank = new BankAccountService(currentUserId).GetBankAccountById(bankAccountId.Value);
model.TransactionReferences = PopulateReferenceDate(model.TransactionReferences, null);
model.BankAccountId = bank.Id;
model.BankAccountName = bank.FullName;
model.Transaction.TransactionLines.Add(new TransactionLine
{
TransactionId = model.Transaction.Id // Link the transaction line to the transaction.
});
var transactionDate = Session["DefaultDate"] != null
? DateTime.Parse(Session["DefaultDate"].ToString())
: DateTime.UtcNow;
// Populate the object to hold the Transaction data, so that we can use it and return it in the view.
model.Transaction.TransactionDate = transactionDate;
}
return View(model);
}
I think you should use the SelectList Constructor in your view, in order to indicate the default value, like this:
#Html.DropDownListFor(
x => x.Transaction.TransactionsLines[0].CategoryId,
new SelectList(Model.TransactionReferences.Categories, "Value", "Text", Model.Transaction.TransactionsLines[0].CategoryId)
)
You are not restricted to use List< SelectListItem > for the collections. You can use a List of a specific class also.
This is the Controller Action Method code:
public class HomeController : Controller
{
public ActionResult Index()
{
var m = new AccountModel();
m.Transaction = new Transaction();
m.Transaction.TransactionsLines = new List<TransactionsLine>();
m.Transaction.TransactionsLines.Add(new TransactionsLine() { CategoryId = 2 });
m.TransactionReferences = new TransactionReferences();
m.TransactionReferences.Categories = new List<SelectListItem>()
{ new SelectListItem() { Text = "Cat1", Value = "1" },
new SelectListItem() { Text = "Cat2", Value = "2" },
new SelectListItem() { Text = "Cat3", Value = "3" }
};
return View(m);
}
}

Populating SelectLists in viewmodels

I have a legacy table represented by the following model:
public class Employee
{
[Key]
[Column("employee_id")]
public string EmployeeId { get; set; }
[Column("first_name")]
public string FirstName { get; set; }
[Column("last_name")]
public string LastName { get; set; }
[Column("active")]
public bool Active { get; set; }
}
I don't have a viewmodel for this class and it will only be used to populate SelectLists (via repository) in other viewmodels in my app. However, I want to create a property like so, to concatenate the first and last names for the SelectLists/dropdown:
private string _EmployeeName;
public string EmployeeName
{
get
{
return _EmployeeName;
}
set
{
_EmployeeName = this.FirstName + " " + this.LastName;
}
}
When I put the EmployeeName in my Employee model, I get an error that the column EmployeeName doesn't exist. Ok, makes sense because this is my model and their is no such column.
Here is an abbreviated example of one viewmodelthat uses the SelectList:
public class EquipmentViewModel
{
[Display(Name = "Equipment ID:")]
public string EquipmentId { get; set; }
[Required(ErrorMessage = "Equipment name is required.")]
[Display(Name = "Equipment Name:")]
[MaxLength(128)]
public string EquipmentName { get; set; }
public SelectList EmployeeList { get; set; }
}
In my controller, I do this:
var emp = iEmployeeRepository.FindBy(x => x.Active == true).OrderBy(x => x.FirstName);
var equipmentViewModel = new EquipmentViewModel
{
EquipmentId = e.EquipmentId,
EquipmentName = e.EquipmentName,
OriginatorEmployeeId = e.OriginatorEmployeeId,
EmployeeList = new SelectList(emp, "EmployeeId", "FirstName"),
};
return View(equipmentViewModel);
Since I don't have a viewmodel for the Employee class, where can I put this EmployeeName property to replace FirstName? If someone could point me in the right direction I'd be grateful.
You don't need an EmployeeName property. Do this in your controller:
var emp = iEmployeeRepository.FindBy(x => x.Active == true)
.OrderBy(x => x.FirstName)
.Select(x => new { EmployeeId = x.EmployeeId, EmployeeName = x.FristName + " " + x.LastName });
var equipmentViewModel = new EquipmentViewModel
{
EquipmentId = e.EquipmentId,
EquipmentName = e.EquipmentName,
OriginatorEmployeeId = e.OriginatorEmployeeId,
EmployeeList = new SelectList(emp, "EmployeeId", "EmployeeName"),
};
return View(equipmentViewModel);

Resources