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

use*_*439 5 c# asp.net-mvc viewmodel razor asp.net-mvc-4

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

public partial class PrinterMapping
{
    public string MTPrinterID { get; set; }
    public string NTPrinterID { get; set; }
    public string Active { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后我有以下视图模型:

public class PrinterViewModel
{
    public PrinterMapping PrinterMapping;
    public Exceptions Exceptions;
    public IEnumerable<PrinterMapping> Printers;
}
Run Code Online (Sandbox Code Playgroud)

在HomeController中的Index Action中,我将视图模型传递给Index视图.

private eFormsEntities db = new eFormsEntities();
public ActionResult Index()
{
    PrinterViewModel printerModel = new PrinterViewModel();
    printerModel.Printers = from pt in db.PrinterMapping select pt;

    return View(printerModel);
}
Run Code Online (Sandbox Code Playgroud)

我的索引视图以下面的方式调用部分视图(可能是错误的):

@Html.Partial("~/Views/Home/GridView.cshtml")
Run Code Online (Sandbox Code Playgroud)

我的GridView.cshtml看起来像:

@model AccessPrinterMapping.Models.PrinterViewModel

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

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

@grid.GetHtml()
Run Code Online (Sandbox Code Playgroud)

我从http://msdn.microsoft.com/en-us/magazine/hh288075.aspx了解了WebGrid方法.

我的WebGrid行根本不开心,因为它不能识别该行中的@model.如何访问我传入的视图模型中的打印机?这甚至可能吗?

非常感谢大家.

Dmy*_*nko 2

@{
    new WebGrid(Model.Printers, "");
}
Run Code Online (Sandbox Code Playgroud)

而且您还必须将模型传递到部分视图中

@Html.Partial("~/Views/Home/GridView.cshtml")
Run Code Online (Sandbox Code Playgroud)

在第二个参数中。我想这个电话应该是

@Html.Partial("~/Views/Home/GridView.cshtml", Model)
Run Code Online (Sandbox Code Playgroud)