Hi @Anjali Agarwal
How can I select the value of the drop down based on the first column value when page loads.
You can create the SelectList instance in the view page and set the selected value based on the Name property of the DocumentModel (created based on the table columns).
Refer to the following code:
Controller:
public IActionResult Index()
{
var docTypes = new List<DocType>()
{
new DocType { Id = 1,Description ="This is Test1"},
new DocType { Id = 2,Description ="This is Test2"},
new DocType { Id = 3,Description ="This is Test3"},
new DocType { Id = 4,Description ="This is Test4"},
new DocType { Id = 5,Description ="This is Test5"},
};
var testmodellist = new List<DocumentModel>()
{
new DocumentModel { DocumentId = 1, Name="Test1", Date= DateTime.Now },
new DocumentModel { DocumentId = 2, Name="Test2", Date=DateTime.Now},
new DocumentModel { DocumentId = 3, Name="Test3", Date=DateTime.Now},
new DocumentModel { DocumentId = 4, Name="Test4", Date=DateTime.Now},
new DocumentModel { DocumentId = 5, Name="Test5", Date=DateTime.Now},
};
//new SelectList(docTypes, "Id", "Description");
ViewData["DocumentType"] = docTypes; //use viewdata transfer list of DocumentType to View Page
return View(testmodellist);
}
View page:
@model IEnumerable<WebApplication1.Models.DocumentModel>
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<table class="table table-bordered">
<thead>
<tr>
<th>FileName</th>
<th>Type</th>
<th>Record Date</th>
</tr>
</thead>
<tbody>
@if (Model != null)
{
@foreach (var item in Model)
{
<tr>
<td>
<label id="lblName_@item.DocumentId">@item.Name</label>
</td>
<td>
<select class="form-control" style="min-width:150px"
id="ddldoc_@item.DocumentId" asp-for="@item.DocumentType"
asp-items="new SelectList(ViewBag.DocumentType, nameof(DocType.Id),
nameof(DocType.Description),
((List<DocType>)ViewBag.DocumentType).Where(c=> c.Description.Contains(item.Name)).FirstOrDefault().Id)"></select>
</td>
<td><label id="lblName_@item.DocumentId">@item.Date</label></td>
</tr>
}
}
</tbody>
</table>
The result as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion