Hi @Anjali Agarwal
You can modify your code as below:
- In the EmployeeInfo class, try to use
List<T>instead ofICollection<T>to add the EmergencyInfos property.
public class EmployeeInfo
{
public int EmployeeInfoId { get; set; }
public string LastName { get; set; } = null!;
public string EmailAddress { get; set; } = null!;
public virtual List<EmergencyInfo> EmergencyInfos { get; set; } = new List<EmergencyInfo>();
}
- In the view page. use the following code to display the properties:
<div class="form-group">
@if (Model != null && Model.EmergencyInfos != null && Model.EmergencyInfos.ToList().Count > 0)
{
var count = Model.EmergencyInfos.Count;
@for (var i = 0; i < count; i++)
{
<div class="form-group row">
<div class="col">
<label class="control-label">LastName</label>
<input asp-for="EmergencyInfos[i].LastName" value="@(string.IsNullOrEmpty(Model.EmergencyInfos.ToList()[i].LastName)? "": @Model.EmergencyInfos.ToList()[i].LastName)" class="form-control" />
<span asp-validation-for="EmergencyInfos[i].LastName" class="text-danger"></span>
</div>
</div>
}
}
else
{
<div class="form-group row">
<div class="col">
<label asp-for="EmergencyInfos[0].LastName" class="control-label">LastName</label>
<input asp-for="EmergencyInfos[0].LastName" class="form-control" />
<span asp-validation-for="EmergencyInfos[0].LastName" class="text-danger"></span>
</div>
</div>
}
</div>
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