C# 在Razor-4视图中访问模型属性

C# 在Razor-4视图中访问模型属性,c#,asp.net-mvc,asp.net-mvc-4,razor,viewmodel,C#,Asp.net Mvc,Asp.net Mvc 4,Razor,Viewmodel,我有以下EF生成的数据模型: public partial class PrinterMapping { public string MTPrinterID { get; set; } public string NTPrinterID { get; set; } public string Active { get; set; } } 然后,我有以下视图模型: public class PrinterViewModel { public PrinterMapp

我有以下EF生成的数据模型:

public partial class PrinterMapping
{
    public string MTPrinterID { get; set; }
    public string NTPrinterID { get; set; }
    public string Active { get; set; }
}
然后,我有以下视图模型:

public class PrinterViewModel
{
    public PrinterMapping PrinterMapping;
    public Exceptions Exceptions;
    public IEnumerable<PrinterMapping> Printers;
}
我的索引视图在末尾以以下方式调用局部视图(可能是错误的):

My GridView.cshtml看起来像:

@model AccessPrinterMapping.Models.PrinterViewModel

<h2> This is Where the Grid Will Show</h2>

@{
    new WebGrid(@model.Printers, "");
}

@grid.GetHtml()
@model AccessPrinterMapping.Models.PrinterViewModel
这是网格将显示的位置
@{
新WebGrid(@model.Printers,“”);
}
@grid.GetHtml()
我从中了解了WebGrid方法

我的WebGrid行一点也不高兴,因为它无法识别该行中的@model。 如何访问传入的视图模型中的打印机?这可能吗

非常感谢大家

@{
    new WebGrid(Model.Printers, "");
}
而且你必须把你的模型传递到部分视图中

@Html.Partial("~/Views/Home/GridView.cshtml")
在第二个参数中。我想这个电话应该是

@Html.Partial("~/Views/Home/GridView.cshtml", Model)

你的代码有两个问题

首先,您应该像这样显式地传入模型:

 @Html.Partial("~/Views/Home/GridView.cshtml", Model) @* explicitly pass the model in *@
然后,因为您已经在局部视图中的代码块中。。您不需要@符号。。而
Model
的大写字母是M

 new WebGrid(Model.Printers, "");

@model
是视图/局部视图的指令。可以将其视为一个“配置”命令<代码>模型是实际属性。它是传递到视图中的对象。。并且是您用
@model
指令指定的类型。

谢谢大家。如果我没有将模型显式地传递给局部视图,您能告诉我发生了什么吗?看来在这种情况下我不需要这么做。其次,@model和model有什么区别?@model只是一个视图模型类型的声明。模型是类型为的视图属性,在@Model声明中声明。另外,如果您不将模型传递到部分视图中,那么模型属性将为null,并且在GridView.cshtml视图中使用模型属性时,您将得到NullReferenceException。感谢Dmytro的解释。通过不显式地将模型传递给局部视图,我似乎没有得到NullReferenceException。但无论如何,这可能是一个好的做法。
 @Html.Partial("~/Views/Home/GridView.cshtml", Model) @* explicitly pass the model in *@
 new WebGrid(Model.Printers, "");