1

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.

  • Shouldn't the tag helper look like: '? – Menahem Jan 12 '19 at 19:38
  • @Menahem before the foreach error happens, and in CreateBrand it works and does not have problem. – Farshad Shahsavari Jan 12 '19 at 19:45
  • Looks like `Model.CategoryBrands` is an empty collection and you are trying to access the first item from that. Refer [Select Tag helper in Asp.net core](https://stackoverflow.com/questions/34624034/select-tag-helper-in-asp-net-core-mvc/34624217#34624217) for samples on how to use select tag helper. – Shyju Jan 12 '19 at 23:23
  • I could not reproduce your problem and It works well. Could you post more reproducible code or share sample on git? – Ryan Jan 14 '19 at 07:25

1 Answers1

0

The problem seems to be that there is a problem with your ViewBag.Categories. Check your ViewBag for its values when there are no categories. A silly fix to it would be to add validation but my suggestion is to useSelectList instead. SelectList will give you lesser flexibility but more robustness in razor view.

Here is a how it is used: ASP.NET MVC Dropdown List From SelectList

Omkar
  • 340
  • 3
  • 14