Home > database >  Error when call model in Layout.cshtml Asp.net
Error when call model in Layout.cshtml Asp.net

Time:06-07

I have an Index.cshtml view that I use a model to create a dropdown list . But I want to use the same model in Layout.cshtml and to do the same and I'm getting this error I would like to know what can I do different to fix it. My idea is reuse the same view model from the Index on the Layout view.

Index.cshtml

@model IEnumerable <SelectListItem>
<select id="subSectionID"
@foreach (var item in Model)
{
<option value="@item.Value">@item.Text</option>
}
</select>

Layout.cshtml

@model IEnumerable <SelectListItem>
<select id="subSectionID"
@foreach (var item in Model)
{
<option value="@item.Value">@item.Text</option>
}
</select>

Controller


   public async Task<ActionResult> Index()
        {
          var subSections = await UtilityResource.GetSubSections();

          var subSectionList = subSections.Select(c => new SelectListItem()

            {
                Text = c.Name,
                Value = c.Id.ToString()

            }).ToList();
            subSectionList = subSectionList.OrderBy(c => c.Text).ToList();
           
            return View(subSectionList);
        }


ViewModel


    public class ViewModel 
    {
        public int SelectedSubSectionId { get; set; }

        public IEnumerable<SelectListItem> SubSections { get; set; }

        public List<VisitVM> VisitVMList { get; set; }

        public string SubSectionName { get; set; }
         
    }
    
}

Error:

The model item passed into the dictionary is of type 'ViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[System.Web.Mvc.SelectListItem]'.

CodePudding user response:

fix the action

var viewModel= new ViewModel{ SubSections = subSectionList};
return View(viewModel);

and Layout and Index views should have this code

@model ViewModel

....

 <select  id="subSectionID" 
         asp-for="@Model.SelectedSubSectionId" asp-items="@Model.SubSections">
         <option value="0" >Select</option>
 </select>
  • Related