【问题标题】:Accessing model properties in Razor-4 view在 Razor-4 视图中访问模型属性
【发布时间】:2013-12-20 18:01:20
【问题描述】:

我有以下 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;
}

在 HomeController 的索引操作中,我将视图模型传递给索引视图。

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

    return View(printerModel);
}

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

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

我的 GridView.cshtml 看起来像:

@model AccessPrinterMapping.Models.PrinterViewModel

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

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

@grid.GetHtml()

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

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

非常感谢大家。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 razor viewmodel


    【解决方案1】:

    您的代码有两个问题。

    首先,您应该像这样显式传递您的模型:

     @Html.Partial("~/Views/Home/GridView.cshtml", Model) @* explicitly pass the model in *@
    

    然后,因为您已经在部分视图中的代码块中..您不需要@符号..并且Model有一个大写的M。

     new WebGrid(Model.Printers, "");
    

    @model 是您的视图/部分视图的指令。将其视为“配置”命令。 Model 是实际财产。它是传递到视图中的对象。它是您使用 @model 指令指定的类型。

    【讨论】:

      【解决方案2】:
      @{
          new WebGrid(Model.Printers, "");
      }
      

      您还必须将模型传递到

      中的局部视图
      @Html.Partial("~/Views/Home/GridView.cshtml")
      

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

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

      【讨论】:

      • 谢谢大家。如果我没有将模型显式传递给局部视图,您能否告诉我会发生这种情况?在这种情况下,我似乎不需要。其次@model和Model有什么区别?
      • @model 只是视图模型类型的声明。 Model 是一个带有类型的视图属性,在@model 声明中声明。此外,如果您不将模型传递到局部视图,则 Model 属性将为 null,当您在 GridView.cshtml 视图中使用 Model 属性时,您将获得 NullReferenceException。
      • 感谢 Dmytro 的解释。看起来我没有通过没有明确地将模型传递给局部视图来获得 NullReferenceException。但无论如何,这样做可能是一种好习惯。
      猜你喜欢
      • 2012-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      相关资源
      最近更新 更多