我有一个名为 LogViewModel 的 ViewModel,我有 3 个属性,如下所示。
public class LogViewModel
{
public IEnumerable<Log> Logs { get; private set; }
public PaginationHelper Pagination { get; set; }
public LogFilter Filter { get; set; }
}
LogViewModel 作为模型传递给 View 。 现在我需要将 LogFilter(带有数据)传递给部分 View ,例如:
@Html.Partial("_LogsFilter", Model.Filter)
我尝试了很多方法,但总是得到同样的错误:
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'.
有什么想法吗?
最佳答案
因为 Filter
属性为 null,框架会将模型从父 View 传递给局部 View ,即 LogViewModel
,而局部 View 期望类型为 日志过滤器
。
要防止这种情况,请确保在呈现 View 之前实例化 Filter
属性,或者执行如下操作:
@Html.Partial("_LogsFilter", Model.Filter ?? new LogFilter())
关于c# - 如何将 ViewModel 属性作为模型传递给局部 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24949949/