c# - 如何将 ViewModel 属性作为模型传递给局部 View ?

标签 c# asp.net asp.net-mvc razor

我有一个名为 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/

相关文章:

c# - 重命名 Windows azure 的暂存 url

java - C# `Interlocked.Exchange(Object, Object) : Object` 的 Java 等价物是什么?

asp.net - 将网页导出到 Excel 时保留 CSS 样式

css - 无法更改文本框的大小

javascript - Datatables.net 渲染和应用分页速度慢

c# - 依赖注入(inject)(使用 SimpleInjector)和 OAuthAuthorizationServerProvider

c# - 重构重复的 Lambda 表达式

c# - 紧凑框架中的透明度

javascript - MVC 中的 JQuery - 使用 getJson 将表单数据作为数组发送

c# - Mono 和 Array.Sort