user3041439
user3041439

Reputation: 153

Accessing model properties in Razor-4 view

I have the following EF generated data model:

public partial class PrinterMapping
{
    public string MTPrinterID { get; set; }
    public string NTPrinterID { get; set; }
    public string Active { get; set; }
}

I then have the following view model:

public class PrinterViewModel
{
    public PrinterMapping PrinterMapping;
    public Exceptions Exceptions;
    public IEnumerable<PrinterMapping> Printers;
}

In my Index Action in HomeController I am passing my view model to the Index view.

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

    return View(printerModel);
}

My Index view is calling a partial view in the following manner towards the end (probably wrong):

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

My GridView.cshtml looks like:

@model AccessPrinterMapping.Models.PrinterViewModel

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

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

@grid.GetHtml()

I learned about the WebGrid method from http://msdn.microsoft.com/en-us/magazine/hh288075.aspx.

My WebGrid line isn't happy at all since it doesn't recognize @model within that line. How do I access the Printers in the view model that I passed in? Is this even possible?

Thanks very much to you all.

Upvotes: 5

Views: 21350

Answers (2)

Simon Whitehead
Simon Whitehead

Reputation: 65079

Theres two issues with your code.

First, you should explicitly pass your model in like this:

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

Then, because you are already in a code block in your partial view.. you don't need the @ symbol.. and Model has an uppercase M.

 new WebGrid(Model.Printers, "");

@model is a directive for your views/partial views. Think of it as a "configuration" command. Model is an actual property. It is the object that is passed into the view.. and is of the type you specified with the @model directive.

Upvotes: 3

Dmytro Rudenko
Dmytro Rudenko

Reputation: 2524

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

and also you have to pass your model into partial view in

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

in second parameter. I guess this call should be

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

Upvotes: 2

Related Questions