I have a asp.net core project. In my model I have one entity that its name is Brand. You can see that below.
public class Brand
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual IList<CategoryBrand> CategoryBrands { get; set; }
}
}
and this is the section of my view that I have problem with that.
<select asp-for="@Model.CategoryBrands[0].CatId">
@foreach (var item in ViewBag.Categories)
{
<option value="@item.Id">@item.Name</option>
}
</select>
When I want to edit one of my entities that does not have any categorybrands I get this error
Index was out of range. Must be non-negative and less than the size of the collection
I understand the error reason, because there is nothing in brand.categorybrands collection, but consider that I need this select, because in EditBrand somebody maybe want to add a category in edit page.