CategoryVM:::::
public class CategoryVM { public Category Category { get; set; } = new Category();
public IEnumerable<Category> Categories { get; set; } = new List<Category>();
}
CategoryController::::
private IUnitOfWork _unitOfWork; public CategoryController(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; }
public IActionResult Index()
{
CategoryVM categoryVM = new CategoryVM();
categoryVM.Categories = _unitOfWork.Category.GetAll();
return View(categoryVM);
}
the code was working fine before adding viewmodel but after adding this I gonna face viewmodel error like:::
An unhandled exception occurred while processing the request. InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'ModelLibrary.ViewModel.CategoryVM', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable`1[ModelLibrary.Models.Category]'.
CodePudding user response:
you have to fix an Index view model, instead of Category should be
@model CategoryVM
.... fix the html data binding accordingly
or if you don't use a Category in your view, you can change model
@model List<Category>
.... fix the html data binding accordingly
but in this case you will have to change the action code too
var model = _unitOfWork.Category.GetAll();
return View(model)
CodePudding user response:
Everything is correct you just need to :
@model IEnumerable<ModelLibrary.Models.Category>
Replace by given blew code because we already made list in ViewModel and upper code is also printing list that's because exception hendling error appearing::