Reputation: 1175
I have a model class
namespace myapp.Models
{
public class SubjectModels
{
[Key]
public int SubjectId { get; set; }
[Required]
public int SubjectType { get; set; }
[Required]
[MinLength(5)]
public string SubjectName { get; set; }
}
}
Here, SubjectType = 1 for Optional and SubjectType = 2 for Compulsory
Now in another class I have to create a drop down for this class,
namespace myapp.Models
{
public class SelectionModels
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SelectionId { get; set; }
[Required]
[MinLength(5)]
public string SelectionDate { get; set; }
[ForeignKey("SubjectId")]
public SubjectModels Subject { get; set; }
public int SubjectId { get; set; }
}
}
When I genereted controller and create.cshtml via scaffolding, my create controller method:
public ActionResult Create()
{
ViewBag.SubjectId = new SelectList(db.Subjects, "SubjectId", "SubjectName");
return View();
}
But I have to create a drop down concatenating the fields "SubjectName" and "SubjectType". Also, display for SubjectType should be Optional and Compulsory not integer.
for example,
"Optional - ResearchMethodology"
"Compulsory - BioChemistry"
How shall I do this? I googled but could not found suitable solutions. Please help!!!
Upvotes: 1
Views: 411
Reputation: 35544
I would create an extra property in the SubjectModels
class.
class SubjectModels
{
public int SubjectId { get; set; }
public int SubjectType { get; set; }
public string SubjectName { get; set; }
public string SubjectNameAndType
{
get
{
return string.Format("{0} - {1}", SubjectName, SubjectType);
}
}
}
Then in the Controller you can use that property to fill the SelectList
var list = new List<SubjectModels>()
{
new SubjectModels()
{
SubjectType = 1,
SubjectName = "Name 1"
},
new SubjectModels()
{
SubjectType = 2,
SubjectName = "Name 2"
}
};
ViewBag.SubjectId = new SelectList(list, "SubjectId", "SubjectNameAndType");
Now you will see the correct values in the DropDownList.
@Html.DropDownListFor(m => m.MyValue, (SelectList)ViewBag.SubjectId, "Select...")
Upvotes: 1