On the create page, I have a dropdown list. And it saves the correct number to the database. When I go back to the "Index" page , it lists all of my records, I want to just see the name chosen. How can I do that?
public class myCrops
{
public static List<Crops> GetAll()
{
return new List<Crops>
{
new Crops() { Id = 1, Name = "Apples"},
new Crops() { Id = 2, Name = "Bananas"},
new Crops() { Id = 3, Name = "Grapes"},
new Crops() { Id = 4, Name = "Orange"},
};
}
}
On the index page , it shows the correct number that was chosen, but I want the name like: ie Bob chose "Grapes" instead of showing the number "3". TIA
"ID" "Name" "Age" "Crop"
42 Bob 23 Grapes
43 Sue 45 Apples
On the create page, I have a dropdown list. And it saves the correct number to the database. When I go back to the "Index" page , it lists all of my records, I want to just see the name chosen. How can I do that?
Actually, all you need a viewModel where you would define CropName as string and fetch the details from database or currently where they are along with your CorpId and bind them into the ViewModel by IDs and get the name from your static list.
Finally, return your viewModel which will display CorpsName in Index page.
Data Structure:
Let's have a look in action, assuming you have your data in following structure,
View Model:
public class FarmerViewModel
{
public int Id { get; set; }
public string? Name { get; set; }
public int Age { get; set; }
public string? CorpsName { get; set; }
}
Index Page Action:
public IActionResult CorpsIndex()
{
var list = _context.Corps.ToList();
var listOfFarmers = new List<FarmerViewModel>();
foreach (var item in list)
{
var model = new FarmerViewModel();
model.Id = item.Id;
model.Name = item.Name;
model.Age = item.Age;
model.CorpsName = myCrops.GetAll().FirstOrDefault(selectedCorps => selectedCorps.Id == item.CorpsId).Name;
listOfFarmers.Add(model);
}
return View(listOfFarmers);
}
View:
@model IEnumerable<YourProjectName.Models.FarmerViewModel>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Id)
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.CorpsName)
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.CorpsName)
</td>
</tr>
}
</tbody>
</table>
Output:
Note: In addition, if your corps has any relation with other table in that scenario you could use entity framework relational key Include in order to laod related data from other table. You can get more details and example here.