Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass ViewModel property as model to partial view?

I have ViewModel called LogViewModel in wich i have 3 properties as shown below.

public class LogViewModel
{
    public IEnumerable<Log> Logs { get; private set; }
    public PaginationHelper Pagination { get; set; }
    public LogFilter Filter { get; set; }
}

LogViewModel is passed to View as Model. Now i need to pass LogFilter (with data) to partial view like:

@Html.Partial("_LogsFilter", Model.Filter)

I tried a lot of methods but always get the same error:

The model item passed into the dictionary is of type 'Infrastructure.Presentation.Desk.ViewModels.LogViewModel', but this dictionary requires a model item of type 'Infrastructure.Presentation.Desk.Models.LogFilter'.

Any thoughts?

like image 449
Jacek Jaskólski Avatar asked Feb 13 '23 10:02

Jacek Jaskólski


1 Answers

Because Filter property is null, the framework will pass the model from the parent view to the partial, which is LogViewModel, while partial view is expecting type of LogFilter.

To prevent this assure that Filter property is instantiated before rendering the view, or do something like this:

@Html.Partial("_LogsFilter", Model.Filter ?? new LogFilter())
like image 184
Zabavsky Avatar answered Feb 15 '23 09:02

Zabavsky